- packages/shared/src/bots.ts: 컴퓨터 id(bot:<n>:<ulid>)·프로필(컴퓨터 n)·BOT_GAMES
(도블·할리갈리·그림 맞히기·마피아 제외)
- packages/games/src/bots: 전략 계약(자기 view + 합법 수만), decideBotAction(validate 재검사),
게임별 <게임>/bot.ts 22개 + 행동 테스트, 전 게임 판 끝까지 돌리는 공통 테스트
- 서버: Room.addBot/removeBot(방장·대기실만, 방은 친구만), RoomManager.createPractice
(POST /api/rooms {practice:true}), BotDriver(사람 같은 지연, 사람과 같은 창이면 더 천천히,
재시작 후 다시 예약), 연습 게임은 전적 제외(result_json.practice), 사람이 모두 나가면 무효
- 프로토콜 addBot/removeBot, 문서 03·06 §12·08·09 §8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
141 lines
6.1 KiB
TypeScript
141 lines
6.1 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { SeededRng, seedN, type PlayerId } from '@bg/engine';
|
|
import { decideBotAction } from '../bots/index';
|
|
import { botPlayout } from '../bots/playout';
|
|
import { __test, allTiles, kindFromCode, mahjong, tileCode, type HandState, type MahjongAction, type MahjongOptions, type MahjongState, type TileId } from './index';
|
|
|
|
const P4 = ['A', 'B', 'C', 'D'];
|
|
|
|
/** Picks tile ids for a notation like "123m55z" (plain copies first, the red five last). */
|
|
function take(notation: string, used: Set<TileId>): TileId[] {
|
|
const out: TileId[] = [];
|
|
for (const m of notation.matchAll(/(\d+)([mpsz])/g)) {
|
|
for (const d of m[1]!) {
|
|
const kind = kindFromCode(`${d}${m[2]}`)!;
|
|
const id = [1, 2, 3, 0].map((c) => kind * 4 + c).find((x) => !used.has(x))!;
|
|
used.add(id);
|
|
out.push(id);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** 4-player hand in progress: seat `turn` has drawn `drawn`; '*' hands are inert single tiles. */
|
|
function rig(o: { hands: string[]; drawn: string; turn?: number; discards?: { seat: number; tiles: string }[]; riichi?: number[] }): MahjongState {
|
|
const s = mahjong.setup({ players: P4, options: mahjong.optionsSchema.parse({}), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
|
|
s.players = [...P4]; // setup shuffles the seats; seat 0 = A = dealer here
|
|
const used = new Set<TileId>();
|
|
const hands = o.hands.map((h) => (h === '*' ? [] : take(h, used)));
|
|
const discards: HandState['discards'] = P4.map(() => []);
|
|
for (const d of o.discards ?? []) for (const t of take(d.tiles, used)) discards[d.seat]!.push({ tile: t, tsumogiri: false, riichi: false, calledBy: null });
|
|
const turn = o.turn ?? 0;
|
|
const drawn = take(o.drawn, used)[0]!;
|
|
const doraInd = take('9m', used);
|
|
// Inert filler: 1·4·7 of each suit plus honors, skipping used copies.
|
|
const inert = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 28, 29, 30, 31, 32, 33];
|
|
o.hands.forEach((h, i) => {
|
|
if (h !== '*') return;
|
|
for (const k of inert) {
|
|
const id = [1, 2, 3, 0].map((c) => k * 4 + c).find((x) => !used.has(x));
|
|
if (id !== undefined && hands[i]!.length < 13) (used.add(id), hands[i]!.push(id));
|
|
}
|
|
});
|
|
const rest = allTiles(false).filter((t) => !used.has(t));
|
|
const empty = <T,>(f: () => T) => P4.map(f);
|
|
const h: HandState = {
|
|
wall: rest.slice(13),
|
|
rinshan: rest.slice(0, 4),
|
|
doraInd: [...doraInd, ...rest.slice(4, 8)],
|
|
uraInd: rest.slice(8, 13),
|
|
doraRevealed: 1,
|
|
pendingKanDora: 0,
|
|
hands,
|
|
drawn: empty(() => null),
|
|
melds: empty(() => []),
|
|
kita: empty(() => []),
|
|
discards,
|
|
riichi: empty(() => null),
|
|
sidewaysNext: empty(() => false),
|
|
tempFuriten: empty(() => false),
|
|
riichiFuriten: empty(() => false),
|
|
waits: empty(() => []),
|
|
turn,
|
|
stage: 'afterDraw',
|
|
interrupted: true,
|
|
kanCount: 0,
|
|
kanBySeat: empty(() => 0),
|
|
lastDrawRinshan: false,
|
|
suukanPending: false,
|
|
kuikae: [],
|
|
pao: empty(() => null),
|
|
claim: null,
|
|
turnStartedAt: 0,
|
|
};
|
|
for (let i = 0; i < 4; i++) h.waits[i] = __test.computeWaits(h, i);
|
|
hands[turn]!.push(drawn);
|
|
h.drawn[turn] = drawn;
|
|
for (const seat of o.riichi ?? []) h.riichi[seat] = { discardIndex: 0, double: false, ippatsu: false };
|
|
s.hand = h;
|
|
s.phase = 'playing';
|
|
return s;
|
|
}
|
|
|
|
const decide = (s: MahjongState, seat: number) => decideBotAction(mahjong, s, P4[seat]!, { now: 1000, random: () => 0.5 }) as MahjongAction;
|
|
const kindOfAction = (a: MahjongAction) => (a.type === 'discard' ? kindFromCode(a.tile.slice(0, 2)) : null);
|
|
const code = (kc: string) => kindFromCode(kc)!;
|
|
/** Seat 0 throws its drawn tile; the claim window opens. */
|
|
function throwDrawn(s: MahjongState): MahjongState {
|
|
const t = s.hand!.drawn[0]!;
|
|
return mahjong.apply(s, 'A', { type: 'discard', tile: tileCode(t, s.red) }, { rng: SeededRng.fromSeed(seedN(2)), now: 1000 }).state;
|
|
}
|
|
|
|
describe('mahjong bot', () => {
|
|
test('wins by tsumo when the drawn tile completes the hand', () => {
|
|
const s = rig({ hands: ['234m567p678s22p34s', '*', '*', '*'], drawn: '5s' });
|
|
expect(decide(s, 0)).toEqual({ type: 'tsumo' });
|
|
});
|
|
|
|
test('declares riichi with a closed tenpai hand, throwing the useless tile', () => {
|
|
const s = rig({ hands: ['234m567p678s22p3s5s', '*', '*', '*'], drawn: '9m' });
|
|
const a = decide(s, 0);
|
|
expect(a).toMatchObject({ type: 'discard', riichi: true });
|
|
expect(kindOfAction(a)).toBe(code('9m'));
|
|
});
|
|
|
|
test('throws an isolated non-yakuhai honor before a number tile', () => {
|
|
const s = rig({ hands: ['123m456p1279s55p8m', '*', '*', '*'], drawn: '3z' });
|
|
const a = decide(s, 0);
|
|
expect(a.type).toBe('discard');
|
|
expect(kindOfAction(a)).toBe(code('3z'));
|
|
});
|
|
|
|
test('pons a dragon, passes on a non-yakuhai honor pon', () => {
|
|
const dragon = throwDrawn(rig({ hands: ['*', '77z135m246p2389s1z', '*', '*'], drawn: '7z' }));
|
|
expect(decide(dragon, 1)).toMatchObject({ type: 'claim', call: 'pon' });
|
|
const west = throwDrawn(rig({ hands: ['*', '33z135m246p2389s1z', '*', '*'], drawn: '3z' }));
|
|
expect(decide(west, 1)).toEqual({ type: 'pass' });
|
|
});
|
|
|
|
test('far from tenpai against a riichi, it throws a tile the riichi player already discarded', () => {
|
|
const s = rig({ hands: ['45m19p19s1234z2s8s7p', '*', '*', '*'], drawn: '6z', discards: [{ seat: 1, tiles: '5m3p' }], riichi: [1] });
|
|
const a = decide(s, 0);
|
|
expect(kindOfAction(a)).toBe(code('5m'));
|
|
});
|
|
|
|
test('bot-only games finish in several modes without stalling a claim window', () => {
|
|
const isBot = (p: PlayerId) => p.startsWith('bot:');
|
|
const cases: [number, Partial<MahjongOptions>][] = [
|
|
[4, { length: 'tonpuu' }],
|
|
[3, { length: 'tonpuu', sanmaTsumo: 'northBisection' }],
|
|
[4, { length: 'tonpuu', akaDora: 0, kuitan: false, doubleRon: 'headBump', abortiveDraws: false }],
|
|
];
|
|
for (const [i, [n, o]] of cases.entries()) {
|
|
const players = Array.from({ length: n }, (_, k) => `bot:${k}:x`);
|
|
const r = botPlayout(mahjong, { players, options: mahjong.optionsSchema.parse(o), seed: seedN(60 + i), isBot, maxSteps: 30_000 });
|
|
expect(r.finished).toBe(true);
|
|
expect(r.botTimeouts).toBe(0);
|
|
expect(r.maxBotMs).toBeLessThan(250);
|
|
}
|
|
});
|
|
});
|