Files
joke-app/packages/games/src/uno/bot.ts
EJClaw 609f458ed2 우노: 공식 규칙 엔진·컴퓨터 상대·화면·도움말·문서·E2E
- 규칙 모듈 packages/games/src/uno: 108장(원카드 색깔 카드 덱·점수 재사용, 원카드 코드는 그대로),
  7장씩, 공식 시작 카드 처리(드로우4 다시 섞기, 드로우2·스킵·리버스, 와일드는 첫 사람이 색 고르기),
  색·숫자·기호 맞추기, 낼 카드가 있어도 뽑기 + 뽑은 카드 바로 내기, 2명 리버스=스킵,
  와일드 드로우4 도전(공식: 몰래 낼 수 있고 성공 4장/실패 6장, 손패는 도전한 사람만) 또는 쉬운 규칙,
  "우노!" 외치기(내면서 또는 직후, 다음 차례 행동 전까지 누구나 잡기 2장), 공식 점수(한 판/500점),
  하우스 룰(드로우 카드 쌓기, 낼 수 있을 때까지 뽑기, 기본 끄기). 시간 초과는 낼 수 있는 카드 자동
  (와일드는 많이 가진 색), 나가기·자리 비움 처리.
- 컴퓨터 상대(bot.ts): 레벨별 우노 깜빡함·잡기 확률, 드로우 카드 아끼기, 드로우4 거짓말/도전 판단, 색 고르기.
- 테스트: 규칙 시나리오, 무작위 대국(유출·보존·결정성), 컴퓨터, 방에서 사람 1 + 컴퓨터 3 끝까지.
- 화면 apps/web/src/games/uno: 지금 색 링·칩, 방향·다음 사람, 남은 장수, 우노 버튼(준비/외치기),
  잡기 버튼, 도전·시작 색·판 결과 창, 30초 요약, 지금 할 수 있는 것.
- 등록(GAMES, 카탈로그, BOT_GAMES/BOT_STRATEGIES, 화면 레지스트리, 아이콘·카드 탭), docs/games/uno.md,
  E2E 계획(PC 1 + 휴대폰 2, 끝까지, 잡기·도전 화면).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:09:33 +09:00

129 lines
5.7 KiB
TypeScript

/**
* 우노 computer player (docs/games/uno.md §9.1). Plays a matching card, keeping wilds for later; saves 드로우2 /
* 와일드 드로우4 for when the next player is close to going out (stronger levels save more); a chosen colour is the
* one it holds most of. The level decides the human parts: easy computers now and then forget to call "우노!",
* notice someone else's missed call less often, challenge at random and may bluff a 와일드 드로우4; hard ones never
* bluff and challenge when the player of the card likely still held the colour.
*/
import type { BotStrategy } from '../bots/types';
import type { BotLevel } from '../bots/persona';
import { humanBest, pick, playable, typeOf } from '../bots/policy';
import { COLORS, majorityColor, type Color, type UnoCard } from './cards';
import type { PlayAction, UnoAction, UnoView } from './types';
/** Chance to forget "우노!" when playing down to one card: 35% at level 1, 15% at 20, gone by 40. */
export function forgetChance(level: BotLevel | undefined): number {
if (level === undefined) return 0;
if (level <= 20) return 0.35 - (0.2 * (Math.max(1, level) - 1)) / 19;
return level < 40 ? (0.05 * (40 - level)) / 20 : 0;
}
/** Chance to catch someone's missed "우노!" when its own turn comes up: 30% at level 1 … always from level 41. */
export function catchChance(level: BotLevel | undefined): number {
if (level === undefined) return 1;
return Math.min(1, 0.3 + (0.7 * (Math.max(1, level) - 1)) / 40);
}
const hard = (level: BotLevel | undefined) => level === undefined || level > 40;
const easy = (level: BotLevel | undefined) => level !== undefined && level <= 20;
/** Seat that plays after me (skipping players who left). */
function nextSeat(view: UnoView): UnoView['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.left) return s;
}
return undefined;
}
function chooseColor(rest: UnoCard[], level: BotLevel | undefined, random: () => number): Color {
if (easy(level) && random() < 0.3) return pick(COLORS, random);
// Ties between colours are broken at random so the choice doesn't give the hand away.
const order = [...COLORS].sort(() => random() - 0.5);
return majorityColor(rest, order);
}
function shouldChallenge(view: UnoView, level: BotLevel | undefined, random: () => number): boolean {
const by = view.seats.find((s) => s.id === view.wild4?.by);
if (!by) return false;
// Wrong: 2 more cards. Right: the player of the card takes the 4. Worth it when they likely held the colour.
if (hard(level)) return by.cards >= 4;
return random() < (easy(level) ? 0.1 : 0.25);
}
export const unoBot: BotStrategy<UnoView, UnoAction> = ({ view, legal, random, level }) => {
const types = new Set(legal.map(typeOf));
if (types.has('ready')) return { type: 'ready' };
const hand = view.my?.hand ?? [];
if (types.has('startColor')) return { type: 'startColor', color: chooseColor(hand, level, random) };
// Its own call (a forgotten one is remembered when its turn comes back), then a catch when it notices.
if (types.has('callUno')) return { type: 'callUno' };
if (types.has('catchUno') && random() < catchChance(level)) return { type: 'catchUno' };
const byId = new Map(hand.map((c) => [c.id, c]));
const ids = [...new Set((legal.filter((a) => a.type === 'play') as PlayAction[]).map((a) => a.cardId))];
const forgot = hand.length === 2 && random() < forgetChance(level);
const finish = (id: string): PlayAction => {
const rest = hand.filter((c) => c.id !== id);
const c = byId.get(id)!;
return {
type: 'play',
cardId: id,
...(c.kind === 'wild' || c.kind === 'wild4' ? { color: chooseColor(rest, level, random) } : {}),
...(hand.length === 2 && !forgot ? { uno: true } : {}),
};
};
if (types.has('challenge')) {
const stack = ids.find((id) => byId.get(id)?.kind === 'wild4');
if (stack) return finish(stack);
return { type: shouldChallenge(view, level, random) ? 'challenge' : 'accept' };
}
if (!ids.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 nextNear = !!next && next.cards <= 2;
const bluffs = new Set(view.my?.bluff ?? []);
const score = (id: string): number => {
const c = byId.get(id)!;
const rest = hand.filter((x) => x.id !== id);
if (rest.length === 0) return 100;
let v = random() * 0.3;
if (view.pending > 0) return v + 10; // stacking beats drawing the pile
switch (c.kind) {
case 'wild':
v -= hard(level) ? 4 : 2.5;
break;
case 'wild4':
v -= 4;
if (bluffs.has(id)) v -= hard(level) ? 30 : easy(level) ? 1 : 6;
if (nextNear) v += 4;
break;
case 'draw2':
// Draw cards hurt most when the next player is about to go out: stronger computers save them for that.
v += nextNear ? 4 : hard(level) ? -0.8 : 0.5;
break;
case 'skip':
case 'reverse':
v += nextNear ? 3 : 0.5;
break;
case 'num':
v += c.value / 20; // high numbers first (they count against me if someone goes out)
break;
}
// Keep my colour going: cards of the colour I hold most of.
if ('color' in c) v += rest.filter((x) => 'color' in x && x.color === c.color).length * 0.3;
return v;
};
const chosen = humanBest(ids, score, random, level, { small: 1, critical: 50 });
// A drawn card that isn't worth playing now (a wild to keep, a bluff) stays in hand.
if (types.has('pass') && score(chosen) < -5) return { type: 'pass' };
return finish(chosen);
};