| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | import { mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs'; |
| 8 | import path from 'node:path'; |
| 9 | import { Table, Heuristic, passIndex, type Ask } from './table'; |
| 10 | import { Bot, REFEREE } from './bots'; |
| 11 | |
| 12 | export const ROOT = path.dirname(REFEREE); |
| 13 | export const SEEDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 14 | const MAX_MOVES = 3000; |
| 15 | const ROLES = ['主公', '忠臣', '反贼', '内奸']; |
| 16 | |
| 17 | |
| 18 | |
| 19 | export async function answer(t: Table, a: Ask, choose: (obs: object, legal: Ask['legal']) => Promise<unknown>): Promise<boolean> { |
| 20 | const refused: unknown[] = []; |
| 21 | for (let k = 0; k < 3; k++) { |
| 22 | const move = await choose(refused.length ? { ...a.obs, refused } : a.obs, a.legal); |
| 23 | if (move === undefined || move === null) break; |
| 24 | if ((await t.act(a.seat, move)) || (await gone(t, a))) return true; |
| 25 | refused.push(move); |
| 26 | } |
| 27 | return pass(t, a); |
| 28 | } |
| 29 | |
| 30 | |
| 31 | export async function gone(t: Table, a: Ask): Promise<boolean> { |
| 32 | return (await t.ask(a.seat))?.key !== a.key; |
| 33 | } |
| 34 | |
| 35 | |
| 36 | export async function pass(t: Table, a: Ask): Promise<boolean> { |
| 37 | const tries: unknown[] = [passIndex(a.legal)]; |
| 38 | const h = new Heuristic(); |
| 39 | for (let k = 0; k < 4; k++) tries.push(h.act({ ...a.obs, refused: tries }, a.legal)); |
| 40 | tries.push(...a.legal.keys()); |
| 41 | for (const m of tries) if ((await t.act(a.seat, m)) || (await gone(t, a))) return true; |
| 42 | return false; |
| 43 | } |
| 44 | |
| 45 | |
| 46 | |
| 47 | async function game(t: Table, bots: Bot[]): Promise<string> { |
| 48 | for (let moves = 0; !t.over; moves++) { |
| 49 | if (moves >= MAX_MOVES) return `${MAX_MOVES} moves`; |
| 50 | const asks = await t.asks(); |
| 51 | if (!asks.length) { |
| 52 | if (!(await t.idle())) return 'stuck: nobody to move'; |
| 53 | continue; |
| 54 | } |
| 55 | const a = asks[0]; |
| 56 | if (!(await answer(t, a, (obs, legal) => bots[a.seat].ask({ obs, legal })))) return `stuck: seat ${a.seat} has no move the engine takes (${a.obs.pending?.requestType})`; |
| 57 | } |
| 58 | return ''; |
| 59 | } |
| 60 | |
| 61 | export function routeName(): string { |
| 62 | const d = (process.env.SS_ROUTE_DIR ?? 'routes').replace(/\/+$/, ''); |
| 63 | return d === 'routes' ? 'main' : d.split('/').slice(1).join('/'); |
| 64 | } |
| 65 | |
| 66 | export function field(): string[] { |
| 67 | const dir = path.join(ROOT, 'field'); |
| 68 | return readdirSync(dir).filter((d) => !d.startsWith('.') && statSync(path.join(dir, d)).isDirectory()).sort(); |
| 69 | } |
| 70 | |
| 71 | |
| 72 | export class Replays { |
| 73 | private index: Array<{ file: string; title: string; seats: string[]; result: string }> = []; |
| 74 | constructor(private root = 'replays') { |
| 75 | mkdirSync(root, { recursive: true }); |
| 76 | } |
| 77 | add(file: string, data: unknown, title: string, seats: string[], result: string): void { |
| 78 | writeFileSync(path.join(this.root, file), JSON.stringify(data)); |
| 79 | this.index.push({ file, title, seats, result }); |
| 80 | writeFileSync(path.join(this.root, 'matches.json'), JSON.stringify(this.index, null, 2)); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | export function writeMetrics(score: number, subtasks: Record<string, number>, file = 'metrics.json'): void { |
| 85 | const r = (x: number) => Math.round(x * 1e6) / 1e6; |
| 86 | const out = { score: r(score), subtasks: Object.fromEntries(Object.entries(subtasks).map(([k, v]) => [k, r(v)])) }; |
| 87 | writeFileSync(file, JSON.stringify(out, null, 2)); |
| 88 | console.log(`score ${out.score} over ${Object.keys(subtasks).length}: ${Object.entries(out.subtasks).map(([k, v]) => `${k} ${v}`).join(', ')}`); |
| 89 | } |
| 90 | |
| 91 | export async function play(mode: string, route: string): Promise<void> { |
| 92 | if (mode !== 'check' && mode !== 'practice') throw new Error('usage: node referee/play.mjs check|practice <route folder>'); |
| 93 | const name = routeName(); |
| 94 | const me = new Bot(route); |
| 95 | const reps = mode === 'practice' ? new Replays() : null; |
| 96 | const won: Record<string, number[]> = Object.fromEntries(ROLES.map((r) => [r, []])); |
| 97 | for (const opp of field()) { |
| 98 | const others = [0, 1, 2, 3].map(() => new Bot(path.join(ROOT, 'field', opp))); |
| 99 | await Promise.all([me.ready, ...others.map((b) => b.ready)]); |
| 100 | for (const seed of mode === 'check' ? SEEDS : SEEDS.slice(0, 1)) { |
| 101 | const roles = await identities(seed); |
| 102 | const mine = mode === 'check' ? [0, 1, 2, 3, 4] : [0, roles.indexOf('反贼')]; |
| 103 | for (const seat of mine) { |
| 104 | const bots = [...others.slice(0, seat), me, ...others.slice(seat)]; |
| 105 | const names = bots.map((b) => (b === me ? name : opp)); |
| 106 | const t = new Table(seed); |
| 107 | await t.open(names); |
| 108 | const why = await game(t, bots); |
| 109 | const role = t.identity(seat); |
| 110 | const win = t.scores()[String(seat)] > 0; |
| 111 | won[role].push(win ? 1 : 0); |
| 112 | console.log(`seed ${seed}, ${name} as ${role} (seat ${seat}) vs ${opp}: ${t.result()}${why ? ` (${why})` : ''}`); |
| 113 | reps?.add(`${opp}-${seed}-${seat}.json`, { ...(t.replay(`${name} vs ${opp}`) as object), shoal: { seat, names } }, |
| 114 | `${name} as ${role}, four ${opp} bots, seed ${seed}`, names, `${t.result()}: ${name} ${win ? 'won' : 'lost'}`); |
| 115 | } |
| 116 | } |
| 117 | others.forEach((b) => b.close()); |
| 118 | } |
| 119 | me.close(); |
| 120 | const rate = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0); |
| 121 | const subtasks = Object.fromEntries(ROLES.filter((r) => won[r].length).map((r) => [r, rate(won[r])])); |
| 122 | if (mode === 'check') writeMetrics(rate(Object.values(subtasks)), subtasks); |
| 123 | } |
| 124 | |
| 125 | |
| 126 | async function identities(seed: number): Promise<string[]> { |
| 127 | const t = new Table(seed); |
| 128 | await t.open(['', '', '', '', '']); |
| 129 | return t.state.players.map((p) => p.identity ?? ''); |
| 130 | } |