diff --git a/src/game/ai/index.ts b/src/game/ai/index.ts new file mode 100644 index 0000000..2b336d7 --- /dev/null +++ b/src/game/ai/index.ts @@ -0,0 +1,75 @@ +// Browser AI opponents (ui-b, issue #5): "easy" and "normal", in ui-a's Bot shape. +// Today they play from the MatchView view model, so they work with the mock engine and any +// adapter. When the shared/game adapter attaches the engine's hidden-information view +// (`view.engine = { view: viewFor(state, seat) }`) and each action's engine form (`action.engine`), +// an engine-level bot can be plugged in through `makeUiBot(level, engineChoice)` (follow-up PR). +// Hard rule (night-lead, #5): bots get only `viewFor` output, never the full MatchState. +// The MatchView never contains the human's queued plays either. +import type { MatchView, UIAction } from '../types.ts'; + +export type BotLevel = 'easy' | 'normal'; +export type Rng = () => number; + +/** ui-a's `Bot` contract (src/game/bots.ts), plus a one-line description for the lobby. */ +export type Bot = { + id: string; + name: string; + description: string; + choose(view: MatchView, legal: UIAction[], rand: Rng): UIAction; +}; + +/** Optional engine-level chooser: gets the engine PlayerView (`viewFor` output only) and returns one engine action. */ +export type EngineChoice = (engineView: { view: unknown }, rng: Rng) => unknown; +type WithEngine = { engine?: unknown }; + +/** Chance that "easy" makes a random move instead of its best one. */ +export const EASY_BLUNDER_RATE = 0.35; + +type Play = Extract; +const END: UIAction = { type: 'endTurn' }; +const stable = (v: unknown): string => JSON.stringify(v, (_k, x) => + x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x); + +/** + * View-model choice. Never concedes or un-queues. Normal plays its strongest card into the lane + * where that card swings the most (taking the lead, or catching up), and ends the turn when no + * card fits. Easy does the same but often plays at random or ends its turn early. + */ +export function viewChoice(level: BotLevel, view: MatchView, legal: UIAction[], rng: Rng): UIAction { + const plays = legal.filter((a): a is Play => a.type === 'play'); + const end = legal.find(a => a.type === 'endTurn') ?? END; + if (!plays.length) return end; + if (level === 'easy' && rng() < EASY_BLUNDER_RATE) return rng() < 0.3 ? end : plays[Math.floor(rng() * plays.length)]; + const power = (id: string) => view.hand.find(c => c.id === id)?.power ?? 0; + const score = (a: Play) => { + const l = view.lanes.find(x => x.index === a.lane); + const mine = (l?.myPower ?? 0) + (l?.staged ?? []).reduce((t, c) => t + c.power, 0); + const gap = (l?.theirPower ?? 0) - mine; // > 0: behind here + const p = power(a.cardId); + const takesLead = gap >= 0 && p > gap ? 4 : 0; + const overkill = gap < -8 ? -3 : 0; // already far ahead: spend elsewhere + return p * 2 + takesLead + overkill + Math.max(-3, Math.min(3, gap)) + rng() * 0.25; + }; + return plays.reduce((best, a) => (score(a) > score(best) ? a : best)); +} + +export function makeUiBot(level: BotLevel, engineChoice?: EngineChoice): Bot { + return { + id: level, + name: level === 'easy' ? 'Easy' : 'Normal', // the lobby renders `${name} bot` + description: level === 'easy' + ? 'Plays big cards, but often makes a random move. Good for learning.' + : 'Plays for the lead in each Topic. It cannot see your hidden plays.', + choose(view, legal, rand) { + const ev = (view as MatchView & { engine?: { view: unknown } }).engine; + const mapped = legal as (UIAction & WithEngine)[]; + if (engineChoice && ev && mapped.length && mapped.every(a => a.engine !== undefined)) { + const wanted = stable(engineChoice(ev, rand)); + return mapped.find(a => stable(a.engine) === wanted) ?? legal.find(a => a.type === 'endTurn') ?? END; + } + return viewChoice(level, view, legal, rand); + }, + }; +} + +export const BOTS: Bot[] = [makeUiBot('easy'), makeUiBot('normal')]; diff --git a/src/game/bots.ts b/src/game/bots.ts index 647928e..5cd6b88 100644 --- a/src/game/bots.ts +++ b/src/game/bots.ts @@ -1,5 +1,6 @@ // AI opponents. ui-b owns the real easy/normal bots in src/game/ai/; this file is the plug-in point. import type { MatchView, UIAction } from './types.ts'; +import { BOTS as AI_BOTS } from './ai/index.ts'; export type Bot = { id: string; name: string; choose(view: MatchView, legal: UIAction[], rand: () => number): UIAction }; @@ -13,4 +14,5 @@ export const randomBot: Bot = { }, }; -export const BOTS: Bot[] = [randomBot]; +/** The lobby's opponents: ui-b's easy and normal bots (src/game/ai). randomBot stays exported as a fallback. */ +export const BOTS: Bot[] = [...AI_BOTS]; diff --git a/tests/ui-bots.test.ts b/tests/ui-bots.test.ts new file mode 100644 index 0000000..aa7b752 --- /dev/null +++ b/tests/ui-bots.test.ts @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { DEFAULT_RULESET } from '../shared/game/index.ts'; +import { engine } from '../src/game/adapter.ts'; +import { BOTS as LOBBY_BOTS, randomBot } from '../src/game/bots.ts'; +import { opponentDeck, starterDeck } from '../src/game/cards.ts'; +import { BOTS, makeUiBot } from '../src/game/ai/index.ts'; +import type { MatchView, PlayerIndex, UIAction } from '../src/game/types.ts'; + +type B = { choose(view: MatchView, legal: UIAction[], rand: () => number): UIAction }; +function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); } + +/** Plays one real-engine match through ui-a's adapter, the way the match screen drives a bot seat. */ +function play(bots: [B, B], seed: string) { + let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed); + const r = rand(seed.length * 7919 + seed.charCodeAt(seed.length - 1)); + for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) { + for (const p of [0, 1] as PlayerIndex[]) { + const legal = engine.legal(s, p); + if (!legal.length) continue; + const pick = bots[p].choose(engine.view(s, p), legal.filter(a => a.type !== 'concede'), r); + assert.notEqual(pick.type, 'concede'); + s = engine.apply(s, p, pick); + } + } + assert.ok(engine.isOver(s), 'match finishes'); + return engine.result(s, 0).winner; +} + +function winRate(a: B, b: B, n: number) { + let score = 0; + for (let i = 0; i < n; i++) { + const flip = i % 2 === 1; + const w = play(flip ? [b, a] : [a, b], `bots-${i}`); + score += w === null ? 0.5 : w === (flip ? 1 : 0) ? 1 : 0; + } + return score / n; +} + +const [easy, normal] = BOTS; + +test('BOTS exports easy and normal in the Bot shape', () => { + assert.deepEqual(BOTS.map(b => b.id), ['easy', 'normal']); + assert.deepEqual(LOBBY_BOTS.map(b => b.id), ['easy', 'normal'], 'the lobby offers the easy and normal bots'); + for (const b of BOTS) assert.ok(b.name && b.description); +}); + +test('normal bot beats random play more than 80% of the time', () => { + const r = winRate(normal, randomBot, 100); + console.log(`normal vs random ${r}`); assert.ok(r > 0.8, `normal vs random ${r}`); +}); + +test('easy bot beats random, and normal beats easy', () => { + const e = winRate(easy, randomBot, 100), g = winRate(normal, easy, 100); + console.log(`easy vs random ${e}, normal vs easy ${g}`); assert.ok(e > 0.5, `easy vs random ${e}`); + assert.ok(g > 0.6, `normal vs easy ${g}`); +}); + +test('bots never concede or un-queue, and end the turn when nothing fits', () => { + const view = { hand: [], lanes: [] } as unknown as MatchView; + for (const b of BOTS) { + const only: UIAction[] = [{ type: 'unstage', cardId: 'x' }, { type: 'concede' }, { type: 'endTurn' }]; + for (let i = 0; i < 20; i++) assert.equal(b.choose(view, only, rand(i)).type, 'endTurn'); + } +}); + +test('an engine-level chooser is used when the adapter attaches engine actions', () => { + const seen: unknown[] = []; + const bot = makeUiBot('normal', (ev, _r) => { seen.push(ev); return { type: 'play', player: 1, cardId: 'b', lane: 2 }; }); + const legal = [ + { type: 'play', cardId: 'a', lane: 0, engine: { type: 'play', player: 1, cardId: 'a', lane: 0 } }, + { type: 'play', cardId: 'b', lane: 2, engine: { lane: 2, cardId: 'b', player: 1, type: 'play' } }, + { type: 'endTurn', engine: { type: 'commit', player: 1 } }, + ] as unknown as UIAction[]; + const view = { hand: [], lanes: [], engine: { view: { you: 1 } } } as unknown as MatchView; + assert.equal(bot.choose(view, legal, rand(1)), legal[1]); + assert.deepEqual(seen, [{ view: { you: 1 } }], 'the engine chooser gets only the viewFor output'); +});