powergrid/ai/strong/bridge.cjs

126 lines
4.9 KiB
JavaScript

const c = require('../core.cjs'),
eco = require('./economics.cjs'),
f = require('./features.cjs'),
readline = require('node:readline');
let envs = [],
sequence = 0;
const seed = process.env.SEED || 'strong-train';
function applyBot(e, p) {
const role = e.roles[p];
if (role === 'legacy') {
const old = Math.random;
Math.random = e.rng;
try {
c.E.moveAI(e.g, p);
} finally {
Math.random = old;
}
} else if (role === 'search') {
const legal = c.candidates(e.g, p),
strategic = legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
c.E.move(
e.g,
strategic
? require('./search.cjs').choose(e.g, p, {
samples: 4,
candidates: 5,
seed: 'arena-search-' + e.g.round + '-' + p + '-' + Math.floor(e.rng() * 1e9),
}).action
: eco.choose(e.g, p, e.rng).action,
p
);
} else
c.E.move(
e.g,
role === 'heuristic' ? c.heuristic(e.g, p, e.rng).action : eco.choose(e.g, p, e.rng, role).action,
p
);
e.steps++;
}
function advance(e) {
while (
!c.E.ended(e.g) &&
e.steps < 1600 &&
!['learner', 'snapshot0', 'snapshot1', 'snapshot2'].includes(e.roles[e.g.currentPlayers[0]])
)
applyBot(e, e.g.currentPlayers[0]);
}
function observation(e) {
if (c.E.ended(e.g) || e.steps >= 1600) return null;
const seat = e.g.currentPlayers[0],
x = f.encode(e.g, seat);
delete x.moves;
return { ...x, episode: e.id, roles: e.roles, round: e.g.round };
}
function reset(mode = 'mixed', arenaSeed, arenaId) {
const id = arenaSeed === undefined ? sequence++ : arenaId,
seat = Math.floor(id / 4) % 3,
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
const opponent =
mode === 'mixed'
? ['economic', 'heuristic', 'rush', 'legacy', 'selfplay', 'snapshot0', 'snapshot1', 'snapshot2'][kind]
: mode;
const roles =
opponent === 'selfplay'
? ['learner', 'learner', 'learner']
: Array.from({ length: 3 }, (_, i) => (i === seat ? 'learner' : opponent));
const gameSeed = arenaSeed === undefined ? seed + '-' + id : arenaSeed + '-' + Math.floor(id / 12);
const e = {
id,
gameSeed,
g: c.start(gameSeed, id % 2 ? 'recharged' : 'original', id % 4 < 2),
roles,
rng: c.seedrandom(arenaSeed === undefined ? seed + '-bot-' + id : gameSeed + '-bot'),
steps: 0,
};
advance(e);
return e;
}
(async () => {
for await (const line of readline.createInterface({ input: process.stdin })) {
try {
const q = JSON.parse(line),
ended = [];
if (q.op === 'reset')
envs = Array.from({ length: q.n }, (_, i) => reset(q.mode, q.arenaSeed, (q.offset || 0) + i));
else if (q.op === 'step')
for (let i = 0; i < envs.length; i++) {
const e = envs[i];
if (q.actions[i] === null) continue;
const seat = e.g.currentPlayers[0];
const legal = c.candidates(e.g, seat),
choice = q.actions[i];
const strategic =
legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
const index = typeof choice === 'object' ? choice.proposal : choice;
const action =
typeof choice === 'object' && strategic
? require('./search.cjs').choose(e.g, seat, {
samples: choice.searchSamples,
candidates: 6,
extraCandidates: [index],
seed: 'arena-guided-' + e.id + '-' + e.steps,
}).action
: legal[index];
c.E.move(e.g, action, seat);
e.steps++;
advance(e);
if (c.E.ended(e.g) || e.steps >= 1600)
ended.push({
env: i,
episode: e.id,
gameSeed: e.gameSeed,
truncated: !c.E.ended(e.g),
value: c.E.ended(e.g) ? c.outcome(e.g) : [0, 0, 0],
steps: e.steps,
roles: e.roles,
});
}
else throw Error('unknown op');
console.log(JSON.stringify({ observations: envs.map(observation), ended }));
} catch (err) {
console.error(err.stack);
process.exit(1);
}
}
})();