Files
joke-app/packages/games/src/one-card/bot.ts

166 lines
7.7 KiB
TypeScript

/**
* 원카드 / 색깔 카드 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 { 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';
import type { OneCardAction, OneCardView, PlayAction } from './types';
/** Seat that plays after me (skipping players that are out). */
function nextSeat(view: OneCardView): OneCardView['seats'][number] | undefined {
const n = view.seats.length;
const i = view.seats.findIndex((s) => s.id === view.me);
for (let k = 1; k < n; k++) {
const s = view.seats[(((i + k * view.direction) % n) + n) % n]!;
if (s.status === 'playing') return s;
}
return undefined;
}
/** Most common suit / colour among `cards` (random among ties or when there is none). */
function majority<K extends string>(keys: K[], all: K[], random: () => number): K {
const count = new Map<K, number>();
for (const k of keys) count.set(k, (count.get(k) ?? 0) + 1);
return best(all, (k) => count.get(k) ?? 0, random);
}
// ---------------------------------------------------------------- 원카드! reaction (docs/games/one-card.md §5.3)
type Window = NonNullable<OneCardView['oneCardWindow']>;
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<Window, 'seq'>, 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<Window, 'seq'>, 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<Window, 'seq'>, 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<OneCardView> = ({ 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<OneCardView, OneCardAction> = ({ me, view, legal, random, level }) => {
const types = new Set(legal.map(typeOf));
if (types.has('ready')) return { type: 'ready' };
// 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[];
const o = view.options;
const uno = view.mode === 'uno-style';
if (types.has('challengeWild4')) {
// Stack a +4 if allowed; otherwise challenge now and then (it is a guess: costs 2 more cards when wrong).
const stack = plays.find((a) => byId.get(a.cardIds[0]!)?.kind === 'wild4');
if (stack) return withChoice(stack, hand, random);
return { type: random() < 0.25 ? 'challengeWild4' : 'acceptWild4' };
}
if (!plays.length) {
if (types.has('pass')) return { type: 'pass' };
if (types.has('draw')) return { type: 'draw' };
return pick(playable(legal), random);
}
const next = nextSeat(view);
const nextNearOut = !!next && next.cards <= 2;
const score = (a: PlayAction): number => {
const cards = a.cardIds.map((id) => byId.get(id)!);
const first = cards[0]!;
const rest = hand.filter((c) => !a.cardIds.includes(c.id));
let v = cards.length * 2 + random() * 0.5;
if (view.pendingAttack > 0) return v + 10; // countering / blocking beats drawing a pile of cards
if (!uno) {
const atk = cards.reduce((x, c) => x + attackOf(o, c), 0);
if (first.kind === 'joker') v -= nextNearOut ? 0 : 4;
else if (atk > 0) v += nextNearOut ? 3 : -1;
if (isStd(first)) {
if (first.rank === 7) v -= 2; // the suit changer is a lifeline: keep it
if (first.rank === 13 && rest.length > 0) v += 1; // K: play again
if (first.rank === 11 || first.rank === 12) v += nextNearOut ? 2 : 0.5;
v += (first.rank >= 11 ? 10 : first.rank) / 20; // dump points first
}
// Don't leave myself only cards that may not finish the hand.
if (rest.length && rest.every((c) => forbiddenAsLast(o, c))) v -= 6;
} else {
if (first.kind === 'wild') v -= 3;
if (first.kind === 'wild4') {
v -= 4;
// Bluffing a +4 while holding the colour risks a challenge.
if (view.currentColor && rest.some((c) => colorOf(c) === view.currentColor)) v -= 3;
if (nextNearOut) v += 3;
}
if (first.kind === 'skip' || first.kind === 'reverse' || first.kind === 'draw2') v += nextNearOut ? 3 : 0.5;
if (first.kind === 'num') v += first.value / 20;
// Keep my colour going: prefer cards of the colour I hold most of.
const c = colorOf(first);
if (c) v += rest.filter((x) => colorOf(x) === c).length * 0.3;
}
return v;
};
return withChoice(best(plays, score, random), hand, random);
};
/** Fixes the suit / colour of a 7 or a wild to the one the rest of the hand holds most of. */
function withChoice(a: PlayAction, hand: Card[], random: () => number): PlayAction {
const rest = hand.filter((c) => !a.cardIds.includes(c.id));
if (a.chooseSuit) {
const suits = rest.filter(isStd).map((c) => c.suit);
return { ...a, chooseSuit: majority<Suit>(suits, SUITS, random) };
}
if (a.chooseColor) {
const colors = rest.map(colorOf).filter((c): c is Color => !!c);
return { ...a, chooseColor: majority<Color>(colors, COLORS, random) };
}
return a;
}