Initial Modpack Upload

This commit is contained in:
Rbanh committed 2023-08-14 21:45:09 -04:00
1 parent 268b0650aa
commit 3d8b956ee4
1429 files changed
+820128

No files matched your search

+393
View File
@@ -0,0 +1,393 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var exhaustive_runner_exports = {};
__export(exhaustive_runner_exports, {
ExhaustiveRunner: () => ExhaustiveRunner
});
module.exports = __toCommonJS(exhaustive_runner_exports);
var import_dex = require("../dex");
var import_prng = require("../prng");
var import_random_player_ai = require("./random-player-ai");
var import_runner = require("./runner");
/**
* Battle Simulator exhaustive runner.
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
const _ExhaustiveRunner = class {
constructor(options) {
this.format = options.format;
this.cycles = options.cycles || _ExhaustiveRunner.DEFAULT_CYCLES;
this.prng = options.prng && !Array.isArray(options.prng) ? options.prng : new import_prng.PRNG(options.prng);
this.log = !!options.log;
this.maxGames = options.maxGames;
this.maxFailures = options.maxFailures || _ExhaustiveRunner.MAX_FAILURES;
this.dual = options.dual || false;
this.failures = 0;
this.games = 0;
}
async run() {
const dex = import_dex.Dex.forFormat(this.format);
dex.loadData();
const seed = this.prng.seed;
const pools = this.createPools(dex);
const createAI = (s, o) => new CoordinatedPlayerAI(s, o, pools);
const generator = new TeamGenerator(dex, this.prng, pools, _ExhaustiveRunner.getSignatures(dex, pools));
do {
this.games++;
try {
const is4P = dex.formats.get(this.format).gameType === "multi";
await new import_runner.Runner({
prng: this.prng,
p1options: { team: generator.generate(), createAI },
p2options: { team: generator.generate(), createAI },
p3options: is4P ? { team: generator.generate(), createAI } : void 0,
p4options: is4P ? { team: generator.generate(), createAI } : void 0,
format: this.format,
dual: this.dual,
error: true
}).run();
if (this.log)
this.logProgress(pools);
} catch (err) {
this.failures++;
console.error(
`
Run \`node tools/simulate exhaustive --cycles=${this.cycles} --format=${this.format} --seed=${seed.join()}\`:
`,
err
);
}
} while ((!this.maxGames || this.games < this.maxGames) && (!this.maxFailures || this.failures < this.maxFailures) && generator.exhausted < this.cycles);
return this.failures;
}
createPools(dex) {
return {
pokemon: new Pool(_ExhaustiveRunner.onlyValid(
dex.gen,
dex.data.Pokedex,
(p) => dex.species.get(p),
(_, p) => p.name !== "Pichu-Spiky-eared" && p.name.substr(0, 8) !== "Pikachu-"
), this.prng),
items: new Pool(_ExhaustiveRunner.onlyValid(dex.gen, dex.data.Items, (i) => dex.items.get(i)), this.prng),
abilities: new Pool(_ExhaustiveRunner.onlyValid(dex.gen, dex.data.Abilities, (a) => dex.abilities.get(a)), this.prng),
moves: new Pool(_ExhaustiveRunner.onlyValid(
dex.gen,
dex.data.Moves,
(m) => dex.moves.get(m),
(m) => m !== "struggle" && (m === "hiddenpower" || m.substr(0, 11) !== "hiddenpower")
), this.prng)
};
}
logProgress(p) {
if (this.games)
process.stdout.write("\r\x1B[K");
process.stdout.write(
`[${this.format}] P:${p.pokemon} I:${p.items} A:${p.abilities} M:${p.moves} = ${this.games}`
);
}
static getSignatures(dex, pools) {
const signatures = /* @__PURE__ */ new Map();
for (const id of pools.items.possible) {
const item = dex.data.Items[id];
if (item.megaEvolves) {
const pokemon = (0, import_dex.toID)(item.megaEvolves);
const combo = { item: id };
let combos = signatures.get(pokemon);
if (!combos) {
combos = [];
signatures.set(pokemon, combos);
}
combos.push(combo);
} else if (item.itemUser) {
for (const user of item.itemUser) {
const pokemon = (0, import_dex.toID)(user);
const combo = { item: id };
if (item.zMoveFrom)
combo.move = (0, import_dex.toID)(item.zMoveFrom);
let combos = signatures.get(pokemon);
if (!combos) {
combos = [];
signatures.set(pokemon, combos);
}
combos.push(combo);
}
}
}
return signatures;
}
static onlyValid(gen, obj, getter, additional, nonStandard) {
return Object.keys(obj).filter((k) => {
const v = getter(k);
return v.gen <= gen && (!v.isNonstandard || !!nonStandard) && (!additional || additional(k, v));
});
}
};
let ExhaustiveRunner = _ExhaustiveRunner;
ExhaustiveRunner.DEFAULT_CYCLES = 1;
ExhaustiveRunner.MAX_FAILURES = 10;
// TODO: Add triple battles once supported by the AI.
ExhaustiveRunner.FORMATS = [
"gen9customgame",
"gen9doublescustomgame",
"gen8customgame",
"gen8doublescustomgame",
"gen7customgame",
"gen7doublescustomgame",
"gen6customgame",
"gen6doublescustomgame",
"gen5customgame",
"gen5doublescustomgame",
"gen4customgame",
"gen4doublescustomgame",
"gen3customgame",
"gen3doublescustomgame",
"gen2customgame",
"gen1customgame"
];
const _TeamGenerator = class {
constructor(dex, prng, pools, signatures) {
this.dex = dex;
this.prng = prng && !Array.isArray(prng) ? prng : new import_prng.PRNG(prng);
this.pools = pools;
this.signatures = signatures;
this.natures = Object.keys(this.dex.data.Natures);
}
get exhausted() {
const exhausted = [this.pools.pokemon.exhausted, this.pools.moves.exhausted];
if (this.dex.gen >= 2)
exhausted.push(this.pools.items.exhausted);
if (this.dex.gen >= 3)
exhausted.push(this.pools.abilities.exhausted);
return Math.min.apply(null, exhausted);
}
generate() {
const team = [];
for (const pokemon of this.pools.pokemon.next(6)) {
const species = this.dex.species.get(pokemon);
const randomEVs = () => this.prng.next(253);
const randomIVs = () => this.prng.next(32);
let item;
const moves = [];
const combos = this.signatures.get(species.id);
if (combos && this.prng.next() > _TeamGenerator.COMBO) {
const combo = this.prng.sample(combos);
item = combo.item;
if (combo.move)
moves.push(combo.move);
} else {
item = this.dex.gen >= 2 ? this.pools.items.next() : "";
}
team.push({
name: species.baseSpecies,
species: species.name,
gender: species.gender,
item,
ability: this.dex.gen >= 3 ? this.pools.abilities.next() : "None",
moves: moves.concat(...this.pools.moves.next(4 - moves.length)),
evs: {
hp: randomEVs(),
atk: randomEVs(),
def: randomEVs(),
spa: randomEVs(),
spd: randomEVs(),
spe: randomEVs()
},
ivs: {
hp: randomIVs(),
atk: randomIVs(),
def: randomIVs(),
spa: randomIVs(),
spd: randomIVs(),
spe: randomIVs()
},
nature: this.prng.sample(this.natures),
level: this.prng.next(50, 100),
happiness: this.prng.next(256),
shiny: this.prng.randomChance(1, 1024)
});
}
return team;
}
};
let TeamGenerator = _TeamGenerator;
// By default, the TeamGenerator generates sets completely at random which unforunately means
// certain signature combinations (eg. Mega Stone/Z Moves which only work for specific Pokemon)
// are unlikely to be chosen. To combat this, we keep a mapping of these combinations and some
// fraction of the time when we are generating sets for these particular Pokemon we give them
// the combinations they need to exercise the simulator more thoroughly.
TeamGenerator.COMBO = 0.5;
class Pool {
constructor(possible, prng) {
this.possible = possible;
this.prng = prng;
this.exhausted = 0;
this.unused = /* @__PURE__ */ new Set();
}
toString() {
return `${this.exhausted} (${this.unused.size}/${this.possible.length})`;
}
reset() {
if (this.filled)
this.exhausted++;
this.iter = void 0;
this.unused = new Set(this.shuffle(this.possible));
if (this.possible.length && this.filled) {
for (const used of this.filled) {
this.unused.delete(used);
}
this.filled = /* @__PURE__ */ new Set();
if (!this.unused.size)
this.reset();
} else {
this.filled = /* @__PURE__ */ new Set();
}
this.filler = this.possible.slice();
}
shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(this.prng.next() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
wasUsed(k) {
this.iter = void 0;
return !this.unused.has(k);
}
markUsed(k) {
this.iter = void 0;
this.unused.delete(k);
}
next(num) {
if (!num)
return this.choose();
const chosen = [];
for (let i = 0; i < num; i++) {
chosen.push(this.choose());
}
return chosen;
}
// Returns the next option in our set of unused options which were shuffled
// before insertion so as to come out in random order. The iterator is
// reset when the pools are manipulated by the CombinedPlayerAI (`markUsed`
// as it mutates the set, but also `wasUsed` because resetting the
// iterator isn't so much 'marking it as invalid' as 'signalling that we
// should move the unused options to the top again').
//
// As the pool of options dwindles, we run into scenarios where `choose`
// will keep returning the same options. This helps ensure they get used,
// but having a game with every Pokemon having the same move or ability etc
// is less realistic, so instead we 'fill' out the remaining choices during a
// generator round (ie. until our iterator gets invalidated during gameplay).
//
// The 'filler' choices are tracked in `filled` to later subtract from the next
// exhaustion cycle of this pool, but in theory we could be so unlucky that
// we loop through our fillers multiple times while dealing with a few stubborn
// remaining options in `unused`, therefore undercounting our `exhausted` total,
// but this is considered to be unlikely enough that we don't care (and
// `exhausted` is a lower bound anyway).
choose() {
if (!this.unused.size)
this.reset();
if (this.iter) {
if (!this.iter.done) {
const next2 = this.iter.next();
this.iter.done = next2.done;
if (!next2.done)
return next2.value;
}
return this.fill();
}
this.iter = this.unused.values();
const next = this.iter.next();
this.iter.done = next.done;
return next.value;
}
fill() {
let length = this.filler.length;
if (!length) {
this.filler = this.possible.slice();
length = this.filler.length;
}
const index = this.prng.next(length);
const element = this.filler[index];
this.filler[index] = this.filler[length - 1];
this.filler.pop();
this.filled.add(element);
return element;
}
}
class CoordinatedPlayerAI extends import_random_player_ai.RandomPlayerAI {
constructor(playerStream, options, pools) {
super(playerStream, options);
this.pools = pools;
}
chooseTeamPreview(team) {
return `team ${this.choosePokemon(team.map((p, i) => ({ slot: i + 1, pokemon: p }))) || 1}`;
}
chooseMove(active, moves) {
this.markUsedIfGmax(active);
for (const { choice, move } of moves) {
const id = this.fixMove(move);
if (!this.pools.moves.wasUsed(id)) {
this.pools.moves.markUsed(id);
return choice;
}
}
return super.chooseMove(active, moves);
}
chooseSwitch(active, switches) {
this.markUsedIfGmax(active);
return this.choosePokemon(switches) || super.chooseSwitch(active, switches);
}
choosePokemon(choices) {
for (const { slot, pokemon } of choices) {
const species = (0, import_dex.toID)(pokemon.details.split(",")[0]);
if (!this.pools.pokemon.wasUsed(species) || !this.pools.abilities.wasUsed(pokemon.baseAbility) || !this.pools.items.wasUsed(pokemon.item) || pokemon.moves.some((m) => !this.pools.moves.wasUsed(this.fixMove(m)))) {
this.pools.pokemon.markUsed(species);
this.pools.abilities.markUsed(pokemon.baseAbility);
this.pools.items.markUsed(pokemon.item);
return slot;
}
}
}
// The move options provided by the simulator have been converted from the name
// which we're tracking, so we need to convert them back.
fixMove(m) {
const id = (0, import_dex.toID)(m.move);
if (id.startsWith("return"))
return "return";
if (id.startsWith("frustration"))
return "frustration";
if (id.startsWith("hiddenpower"))
return "hiddenpower";
return id;
}
// Gigantamax Pokemon need to be special cased for tracking because the current
// tracking only works if you can switch in a Pokemon.
markUsedIfGmax(active) {
if (active && !active.canDynamax && active.maxMoves && active.maxMoves.gigantamax) {
this.pools.pokemon.markUsed((0, import_dex.toID)(active.maxMoves.gigantamax));
}
}
}
//# sourceMappingURL=exhaustive-runner.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../sim/tools/exhaustive-runner.ts"],
"sourcesContent": ["/**\r\n * Battle Simulator exhaustive runner.\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {ObjectReadWriteStream} from '../../lib/streams';\r\nimport {Dex, toID} from '../dex';\r\nimport {PRNG, PRNGSeed} from '../prng';\r\nimport {RandomPlayerAI} from './random-player-ai';\r\nimport {AIOptions, Runner} from './runner';\r\n\r\ninterface Pools {\r\n\tpokemon: Pool;\r\n\titems: Pool;\r\n\tabilities: Pool;\r\n\tmoves: Pool;\r\n}\r\n\r\nexport interface ExhaustiveRunnerOptions {\r\n\tformat: string;\r\n\tcycles?: number;\r\n\tprng?: PRNG | PRNGSeed | null;\r\n\tlog?: boolean;\r\n\tmaxGames?: number;\r\n\tmaxFailures?: number;\r\n\tdual?: boolean | 'debug';\r\n}\r\n\r\nexport class ExhaustiveRunner {\r\n\tstatic readonly DEFAULT_CYCLES = 1;\r\n\tstatic readonly MAX_FAILURES = 10;\r\n\r\n\t// TODO: Add triple battles once supported by the AI.\r\n\tstatic readonly FORMATS = [\r\n\t\t'gen9customgame', 'gen9doublescustomgame',\r\n\t\t'gen8customgame', 'gen8doublescustomgame',\r\n\t\t'gen7customgame', 'gen7doublescustomgame',\r\n\t\t'gen6customgame', 'gen6doublescustomgame',\r\n\t\t'gen5customgame', 'gen5doublescustomgame',\r\n\t\t'gen4customgame', 'gen4doublescustomgame',\r\n\t\t'gen3customgame', 'gen3doublescustomgame',\r\n\t\t'gen2customgame',\r\n\t\t'gen1customgame',\r\n\t];\r\n\r\n\tprivate readonly format: string;\r\n\tprivate readonly cycles: number;\r\n\tprivate readonly prng: PRNG;\r\n\tprivate readonly log: boolean;\r\n\tprivate readonly maxGames?: number;\r\n\tprivate readonly maxFailures?: number;\r\n\tprivate readonly dual: boolean | 'debug';\r\n\r\n\tprivate failures: number;\r\n\tprivate games: number;\r\n\r\n\tconstructor(options: ExhaustiveRunnerOptions) {\r\n\t\tthis.format = options.format;\r\n\t\tthis.cycles = options.cycles || ExhaustiveRunner.DEFAULT_CYCLES;\r\n\t\tthis.prng = (options.prng && !Array.isArray(options.prng)) ?\r\n\t\t\toptions.prng : new PRNG(options.prng);\r\n\t\tthis.log = !!options.log;\r\n\t\tthis.maxGames = options.maxGames;\r\n\t\tthis.maxFailures = options.maxFailures || ExhaustiveRunner.MAX_FAILURES;\r\n\t\tthis.dual = options.dual || false;\r\n\r\n\t\tthis.failures = 0;\r\n\t\tthis.games = 0;\r\n\t}\r\n\r\n\tasync run() {\r\n\t\tconst dex = Dex.forFormat(this.format);\r\n\t\tdex.loadData(); // FIXME: This is required for `dex.gen` to be set properly...\r\n\r\n\t\tconst seed = this.prng.seed;\r\n\t\tconst pools = this.createPools(dex);\r\n\t\tconst createAI = (s: ObjectReadWriteStream<string>, o: AIOptions) => new CoordinatedPlayerAI(s, o, pools);\r\n\t\tconst generator = new TeamGenerator(dex, this.prng, pools, ExhaustiveRunner.getSignatures(dex, pools));\r\n\r\n\t\tdo {\r\n\t\t\tthis.games++;\r\n\t\t\ttry {\r\n\t\t\t\tconst is4P = dex.formats.get(this.format).gameType === 'multi';\r\n\t\t\t\t// We run these sequentially instead of async so that the team generator\r\n\t\t\t\t// and the AI can coordinate usage properly.\r\n\t\t\t\tawait new Runner({\r\n\t\t\t\t\tprng: this.prng,\r\n\t\t\t\t\tp1options: {team: generator.generate(), createAI},\r\n\t\t\t\t\tp2options: {team: generator.generate(), createAI},\r\n\t\t\t\t\tp3options: is4P ? {team: generator.generate(), createAI} : undefined,\r\n\t\t\t\t\tp4options: is4P ? {team: generator.generate(), createAI} : undefined,\r\n\t\t\t\t\tformat: this.format,\r\n\t\t\t\t\tdual: this.dual,\r\n\t\t\t\t\terror: true,\r\n\t\t\t\t}).run();\r\n\r\n\t\t\t\tif (this.log) this.logProgress(pools);\r\n\t\t\t} catch (err) {\r\n\t\t\t\tthis.failures++;\r\n\t\t\t\tconsole.error(\r\n\t\t\t\t\t`\\n\\nRun \\`node tools/simulate exhaustive --cycles=${this.cycles} ` +\r\n\t\t\t\t\t\t`--format=${this.format} --seed=${seed.join()}\\`:\\n`,\r\n\t\t\t\t\terr\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t} while ((!this.maxGames || this.games < this.maxGames) &&\r\n\t\t\t\t\t(!this.maxFailures || this.failures < this.maxFailures) &&\r\n\t\t\t\t\tgenerator.exhausted < this.cycles);\r\n\r\n\t\treturn this.failures;\r\n\t}\r\n\r\n\tprivate createPools(dex: typeof Dex): Pools {\r\n\t\treturn {\r\n\t\t\tpokemon: new Pool(ExhaustiveRunner.onlyValid(dex.gen, dex.data.Pokedex, p => dex.species.get(p),\r\n\t\t\t\t(_, p) => (p.name !== 'Pichu-Spiky-eared' && p.name.substr(0, 8) !== 'Pikachu-')), this.prng),\r\n\t\t\titems: new Pool(ExhaustiveRunner.onlyValid(dex.gen, dex.data.Items, i => dex.items.get(i)), this.prng),\r\n\t\t\tabilities: new Pool(ExhaustiveRunner.onlyValid(dex.gen, dex.data.Abilities, a => dex.abilities.get(a)), this.prng),\r\n\t\t\tmoves: new Pool(ExhaustiveRunner.onlyValid(dex.gen, dex.data.Moves, m => dex.moves.get(m),\r\n\t\t\t\tm => (m !== 'struggle' && (m === 'hiddenpower' || m.substr(0, 11) !== 'hiddenpower'))), this.prng),\r\n\t\t};\r\n\t}\r\n\r\n\tprivate logProgress(p: Pools) {\r\n\t\t// `\\r` = return to the beginning of the line\r\n\t\t// `\\x1b[k` (`\\e[K`) = clear all characters from cursor position to EOL\r\n\t\tif (this.games) process.stdout.write('\\r\\x1b[K');\r\n\t\t/Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAwB;AACxB,kBAA6B;AAC7B,8BAA6B;AAC7B,oBAAgC;AAXhC;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BO,MAAM,oBAAN,MAAuB;AAAA,EA4B7B,YAAY,SAAkC;AAC7C,SAAK,SAAS,QAAQ;AACtB,SAAK,SAAS,QAAQ,UAAU,kBAAiB;AACjD,SAAK,OAAQ,QAAQ,QAAQ,CAAC,MAAM,QAAQ,QAAQ,IAAI,IACvD,QAAQ,OAAO,IAAI,iBAAK,QAAQ,IAAI;AACrC,SAAK,MAAM,CAAC,CAAC,QAAQ;AACrB,SAAK,WAAW,QAAQ;AACxB,SAAK,cAAc,QAAQ,eAAe,kBAAiB;AAC3D,SAAK,OAAO,QAAQ,QAAQ;AAE5B,SAAK,WAAW;AAChB,SAAK,QAAQ;AAAA,EACd;AAAA,EAEA,MAAM,MAAM;AACX,UAAM,MAAM,eAAI,UAAU,KAAK,MAAM;AACrC,QAAI,SAAS;AAEb,UAAM,OAAO,KAAK,KAAK;AACvB,UAAM,QAAQ,KAAK,YAAY,GAAG;AAClC,UAAM,WAAW,CAAC,GAAkC,MAAiB,IAAI,oBAAoB,GAAG,GAAG,KAAK;AACxG,UAAM,Y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AAU;AAAA,UACf,KAAK,UAAU;AAAA,UACf,KAAK,UAAU;AAAA,UACf,KAAK,UAAU;AAAA,QAChB;AAAA,QACA,QAAQ,KAAK,KAAK,OAAO,KAAK,OAAO;AAAA,QACrC,OAAO,KAAK,KAAK,KAAKLine truncated
"names": ["next"]
}
+114
View File
@@ -0,0 +1,114 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var multi_random_runner_exports = {};
__export(multi_random_runner_exports, {
MultiRandomRunner: () => MultiRandomRunner
});
module.exports = __toCommonJS(multi_random_runner_exports);
var import_prng = require("../prng");
var import_runner = require("./runner");
/**
* Battle Simulator multi random runner.
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
const _MultiRandomRunner = class {
constructor(options) {
this.options = { ...options };
this.totalGames = options.totalGames;
this.prng = options.prng && !Array.isArray(options.prng) ? options.prng : new import_prng.PRNG(options.prng);
this.options.prng = this.prng;
this.format = options.format;
this.cycle = !!options.cycle;
this.all = !!options.all;
this.isAsync = !!options.async;
this.formatIndex = 0;
this.numGames = 0;
}
async run() {
let games = [];
let format;
let lastFormat = false;
let failures = 0;
while (format = this.getNextFormat()) {
if (this.all && lastFormat && format !== lastFormat) {
if (this.isAsync)
await Promise.all(games);
games = [];
}
const seed = this.prng.seed;
const game = new import_runner.Runner({ format, ...this.options }).run().catch((err) => {
failures++;
console.error(
`Run \`node tools/simulate multi 1 --format=${format} --seed=${seed.join()}\` to debug (optionally with \`--output\` and/or \`--input\` for more info):
`,
err
);
});
if (!this.isAsync)
await game;
games.push(game);
lastFormat = format;
}
if (this.isAsync)
await Promise.all(games);
return failures;
}
getNextFormat() {
const FORMATS = _MultiRandomRunner.FORMATS;
if (this.formatIndex > FORMATS.length)
return false;
if (this.numGames++ < this.totalGames) {
if (this.format) {
return this.format;
} else if (this.all) {
return FORMATS[this.formatIndex];
} else if (this.cycle) {
const format = FORMATS[this.formatIndex];
this.formatIndex = (this.formatIndex + 1) % FORMATS.length;
return format;
} else {
return this.prng.sample(FORMATS);
}
} else if (this.all) {
this.numGames = 1;
this.formatIndex++;
return FORMATS[this.formatIndex];
}
return false;
}
};
let MultiRandomRunner = _MultiRandomRunner;
MultiRandomRunner.FORMATS = [
"gen8randombattle",
"gen8randomdoublesbattle",
"gen8battlefactory",
"gen7randombattle",
"gen7randomdoublesbattle",
"gen7battlefactory",
"gen6randombattle",
"gen6battlefactory",
"gen5randombattle",
"gen4randombattle",
"gen3randombattle",
"gen2randombattle",
"gen1randombattle"
];
//# sourceMappingURL=multi-random-runner.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../sim/tools/multi-random-runner.ts"],
"sourcesContent": ["/**\r\n * Battle Simulator multi random runner.\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {PRNG, PRNGSeed} from '../prng';\r\nimport {Runner, RunnerOptions} from './runner';\r\n\r\n// @ts-ignore\r\nexport interface MultiRandomRunnerOptions extends RunnerOptions {\r\n\ttotalGames: number;\r\n\tprng?: PRNG | PRNGSeed | null;\r\n\tformat?: string;\r\n\tcycle?: boolean;\r\n\tall?: boolean;\r\n\tasync?: boolean;\r\n}\r\n\r\nexport class MultiRandomRunner {\r\n\tstatic readonly FORMATS = [\r\n\t\t'gen8randombattle', 'gen8randomdoublesbattle', 'gen8battlefactory',\r\n\t\t'gen7randombattle', 'gen7randomdoublesbattle', 'gen7battlefactory',\r\n\t\t'gen6randombattle', 'gen6battlefactory',\r\n\t\t'gen5randombattle',\r\n\t\t'gen4randombattle',\r\n\t\t'gen3randombattle',\r\n\t\t'gen2randombattle',\r\n\t\t'gen1randombattle',\r\n\t];\r\n\r\n\tprivate readonly options: Partial<RunnerOptions>;\r\n\tprivate readonly totalGames: number;\r\n\tprivate readonly prng: PRNG;\r\n\tprivate readonly format: string | undefined;\r\n\tprivate readonly cycle: boolean;\r\n\tprivate readonly all: boolean;\r\n\tprivate readonly isAsync: boolean;\r\n\r\n\tprivate formatIndex: number;\r\n\tprivate numGames: number;\r\n\r\n\tconstructor(options: MultiRandomRunnerOptions) {\r\n\t\tthis.options = {...options};\r\n\r\n\t\tthis.totalGames = options.totalGames;\r\n\r\n\t\tthis.prng = (options.prng && !Array.isArray(options.prng)) ?\r\n\t\t\toptions.prng : new PRNG(options.prng);\r\n\t\tthis.options.prng = this.prng;\r\n\r\n\t\tthis.format = options.format;\r\n\t\tthis.cycle = !!options.cycle;\r\n\t\tthis.all = !!options.all;\r\n\r\n\t\tthis.isAsync = !!options.async;\r\n\r\n\t\tthis.formatIndex = 0;\r\n\t\tthis.numGames = 0;\r\n\t}\r\n\r\n\tasync run() {\r\n\t\tlet games = [];\r\n\t\tlet format: string | false;\r\n\t\tlet lastFormat: string | false = false;\r\n\t\tlet failures = 0;\r\n\t\twhile ((format = this.getNextFormat())) {\r\n\t\t\tif (this.all && lastFormat && format !== lastFormat) {\r\n\t\t\t\tif (this.isAsync) await Promise.all(games);\r\n\t\t\t\tgames = [];\r\n\t\t\t}\r\n\r\n\t\t\tconst seed = this.prng.seed;\r\n\t\t\tconst game = new Runner({format, ...this.options}).run().catch(err => {\r\n\t\t\t\tfailures++;\r\n\t\t\t\tconsole.error(\r\n\t\t\t\t\t`Run \\`node tools/simulate multi 1 --format=${format} --seed=${seed.join()}\\` ` +\r\n\t\t\t\t\t`to debug (optionally with \\`--output\\` and/or \\`--input\\` for more info):\\n`,\r\n\t\t\t\t\terr\r\n\t\t\t\t);\r\n\t\t\t});\r\n\r\n\t\t\tif (!this.isAsync) await game;\r\n\t\t\tgames.push(game);\r\n\t\t\tlastFormat = format;\r\n\t\t}\r\n\r\n\t\tif (this.isAsync) await Promise.all(games);\r\n\t\treturn failures;\r\n\t}\r\n\r\n\tprivate getNextFormat() {\r\n\t\tconst FORMATS = MultiRandomRunner.FORMATS;\r\n\t\tif (this.formatIndex > FORMATS.length) return false;\r\n\r\n\t\tif (this.numGames++ < this.totalGames) {\r\n\t\t\tif (this.format) {\r\n\t\t\t\treturn this.format;\r\n\t\t\t} else if (this.all) {\r\n\t\t\t\treturn FORMATS[this.formatIndex];\r\n\t\t\t} else if (this.cycle) {\r\n\t\t\t\tconst format = FORMATS[this.formatIndex];\r\n\t\t\t\tthis.formatIndex = (this.formatIndex + 1) % FORMATS.length;\r\n\t\t\t\treturn format;\r\n\t\t\t} else {\r\n\t\t\t\treturn this.prng.sample(FORMATS);\r\n\t\t\t}\r\n\t\t} else if (this.all) {\r\n\t\t\tthis.numGames = 1;\r\n\t\t\tthis.formatIndex++;\r\n\t\t\treturn FORMATS[this.formatIndex];\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n}\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,kBAA6B;AAC7B,oBAAoC;AARpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,MAAM,qBAAN,MAAwB;AAAA,EAuB9B,YAAY,SAAmC;AAC9C,SAAK,UAAU,EAAC,GAAG,QAAO;AAE1B,SAAK,aAAa,QAAQ;AAE1B,SAAK,OAAQ,QAAQ,QAAQ,CAAC,MAAM,QAAQ,QAAQ,IAAI,IACvD,QAAQ,OAAO,IAAI,iBAAK,QAAQ,IAAI;AACrC,SAAK,QAAQ,OAAO,KAAK;AAEzB,SAAK,SAAS,QAAQ;AACtB,SAAK,QAAQ,CAAC,CAAC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WAAK,WAAW;AAChB,WAAK;AACL,aAAO,QAAQ,KAAK,WAAW;AAAA,IAChC;AAEA,WAAO;AAAA,EACR;AACD;AAhGO,IAAM,oBAAN;AAAM,kBACI,UAAU;AAAA,EACzB;AAAA,EAAoB;AAAA,EAA2B;AAAA,EAC/C;AAAA,EAAoB;AAAA,EAA2B;AAAA,EAC/C;AAAA,EAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;",
"names": []
}
+185
View File
@@ -0,0 +1,185 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var random_player_ai_exports = {};
__export(random_player_ai_exports, {
RandomPlayerAI: () => RandomPlayerAI
});
module.exports = __toCommonJS(random_player_ai_exports);
var import_battle_stream = require("../battle-stream");
var import_prng = require("../prng");
/**
* Example random player AI.
*
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
class RandomPlayerAI extends import_battle_stream.BattlePlayer {
constructor(playerStream, options = {}, debug = false) {
super(playerStream, debug);
this.move = options.move || 1;
this.mega = options.mega || 0;
this.prng = options.seed && !Array.isArray(options.seed) ? options.seed : new import_prng.PRNG(options.seed);
}
receiveError(error) {
if (error.message.startsWith("[Unavailable choice]"))
return;
throw error;
}
receiveRequest(request) {
if (request.wait) {
} else if (request.forceSwitch) {
const pokemon = request.side.pokemon;
const chosen = [];
const choices = request.forceSwitch.map((mustSwitch, i) => {
if (!mustSwitch)
return `pass`;
const canSwitch = range(1, 6).filter((j) => pokemon[j - 1] && // not active
j > request.forceSwitch.length && // not chosen for a simultaneous switch
!chosen.includes(j) && // not fainted or fainted and using Revival Blessing
!!(+!!pokemon[i].reviving ^ +!pokemon[j - 1].condition.endsWith(` fnt`)));
if (!canSwitch.length)
return `pass`;
const target = this.chooseSwitch(
request.active,
canSwitch.map((slot) => ({ slot, pokemon: pokemon[slot - 1] }))
);
chosen.push(target);
return `switch ${target}`;
});
this.choose(choices.join(`, `));
} else if (request.active) {
let [canMegaEvo, canUltraBurst, canZMove, canDynamax, canTerastallize] = [true, true, true, true, true];
const pokemon = request.side.pokemon;
const chosen = [];
const choices = request.active.map((active, i) => {
if (pokemon[i].condition.endsWith(` fnt`) || pokemon[i].commanding)
return `pass`;
canMegaEvo = canMegaEvo && active.canMegaEvo;
canUltraBurst = canUltraBurst && active.canUltraBurst;
canZMove = canZMove && !!active.canZMove;
canDynamax = canDynamax && !!active.canDynamax;
canTerastallize = canTerastallize && !!active.canTerastallize;
const change = (canMegaEvo || canUltraBurst || canDynamax) && this.prng.next() < this.mega;
const useMaxMoves = !active.canDynamax && active.maxMoves || change && canDynamax;
const possibleMoves = useMaxMoves ? active.maxMoves.maxMoves : active.moves;
let canMove = range(1, possibleMoves.length).filter((j) => // not disabled
!possibleMoves[j - 1].disabled).map((j) => ({
slot: j,
move: possibleMoves[j - 1].move,
target: possibleMoves[j - 1].target,
zMove: false
}));
if (canZMove) {
canMove.push(...range(1, active.canZMove.length).filter((j) => active.canZMove[j - 1]).map((j) => ({
slot: j,
move: active.canZMove[j - 1].move,
target: active.canZMove[j - 1].target,
zMove: true
})));
}
const hasAlly = pokemon.length > 1 && !pokemon[i ^ 1].condition.endsWith(` fnt`);
const filtered = canMove.filter((m) => m.target !== `adjacentAlly` || hasAlly);
canMove = filtered.length ? filtered : canMove;
const moves = canMove.map((m) => {
let move = `move ${m.slot}`;
if (request.active.length > 1) {
if ([`normal`, `any`, `adjacentFoe`].includes(m.target)) {
move += ` ${1 + Math.floor(this.prng.next() * 2)}`;
}
if (m.target === `adjacentAlly`) {
move += ` -${(i ^ 1) + 1}`;
}
if (m.target === `adjacentAllyOrSelf`) {
if (hasAlly) {
move += ` -${1 + Math.floor(this.prng.next() * 2)}`;
} else {
move += ` -${i + 1}`;
}
}
}
if (m.zMove)
move += ` zmove`;
return { choice: move, move: m };
});
const canSwitch = range(1, 6).filter((j) => pokemon[j - 1] && // not active
!pokemon[j - 1].active && // not chosen for a simultaneous switch
!chosen.includes(j) && // not fainted
!pokemon[j - 1].condition.endsWith(` fnt`));
const switches = active.trapped ? [] : canSwitch;
if (switches.length && (!moves.length || this.prng.next() > this.move)) {
const target = this.chooseSwitch(
active,
canSwitch.map((slot) => ({ slot, pokemon: pokemon[slot - 1] }))
);
chosen.push(target);
return `switch ${target}`;
} else if (moves.length) {
const move = this.chooseMove(active, moves);
if (move.endsWith(` zmove`)) {
canZMove = false;
return move;
} else if (change) {
if (canTerastallize) {
canTerastallize = false;
return `${move} terastallize`;
} else if (canDynamax) {
canDynamax = false;
return `${move} dynamax`;
} else if (canMegaEvo) {
canMegaEvo = false;
return `${move} mega`;
} else {
canUltraBurst = false;
return `${move} ultra`;
}
} else {
return move;
}
} else {
throw new Error(`${this.constructor.name} unable to make choice ${i}. request='${request}', chosen='${chosen}', (mega=${canMegaEvo}, ultra=${canUltraBurst}, zmove=${canZMove}, dynamax='${canDynamax}', terastallize=${canTerastallize})`);
}
});
this.choose(choices.join(`, `));
} else {
this.choose(this.chooseTeamPreview(request.side.pokemon));
}
}
chooseTeamPreview(team) {
return `default`;
}
chooseMove(active, moves) {
return this.prng.sample(moves).choice;
}
chooseSwitch(active, switches) {
return this.prng.sample(switches).slot;
}
}
function range(start, end, step = 1) {
if (end === void 0) {
end = start;
start = 0;
}
const result = [];
for (; start <= end; start += step) {
result.push(start);
}
return result;
}
//# sourceMappingURL=random-player-ai.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../sim/tools/random-player-ai.ts"],
"sourcesContent": ["/**\r\n * Example random player AI.\r\n *\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {ObjectReadWriteStream} from '../../lib/streams';\r\nimport {BattlePlayer} from '../battle-stream';\r\nimport {PRNG, PRNGSeed} from '../prng';\r\n\r\nexport class RandomPlayerAI extends BattlePlayer {\r\n\tprotected readonly move: number;\r\n\tprotected readonly mega: number;\r\n\tprotected readonly prng: PRNG;\r\n\r\n\tconstructor(\r\n\t\tplayerStream: ObjectReadWriteStream<string>,\r\n\t\toptions: {move?: number, mega?: number, seed?: PRNG | PRNGSeed | null } = {},\r\n\t\tdebug = false\r\n\t) {\r\n\t\tsuper(playerStream, debug);\r\n\t\tthis.move = options.move || 1.0;\r\n\t\tthis.mega = options.mega || 0;\r\n\t\tthis.prng = options.seed && !Array.isArray(options.seed) ? options.seed : new PRNG(options.seed);\r\n\t}\r\n\r\n\treceiveError(error: Error) {\r\n\t\t// If we made an unavailable choice we will receive a followup request to\r\n\t\t// allow us the opportunity to correct our decision.\r\n\t\tif (error.message.startsWith('[Unavailable choice]')) return;\r\n\t\tthrow error;\r\n\t}\r\n\r\n\treceiveRequest(request: AnyObject) {\r\n\t\tif (request.wait) {\r\n\t\t\t// wait request\r\n\t\t\t// do nothing\r\n\t\t} else if (request.forceSwitch) {\r\n\t\t\t// switch request\r\n\t\t\tconst pokemon = request.side.pokemon;\r\n\t\t\tconst chosen: number[] = [];\r\n\t\t\tconst choices = request.forceSwitch.map((mustSwitch: AnyObject, i: number) => {\r\n\t\t\t\tif (!mustSwitch) return `pass`;\r\n\r\n\t\t\t\tconst canSwitch = range(1, 6).filter(j => (\r\n\t\t\t\t\tpokemon[j - 1] &&\r\n\t\t\t\t\t// not active\r\n\t\t\t\t\tj > request.forceSwitch.length &&\r\n\t\t\t\t\t// not chosen for a simultaneous switch\r\n\t\t\t\t\t!chosen.includes(j) &&\r\n\t\t\t\t\t// not fainted or fainted and using Revival Blessing\r\n\t\t\t\t\t!!(+!!pokemon[i].reviving ^ +!pokemon[j - 1].condition.endsWith(` fnt`))\r\n\t\t\t\t));\r\n\r\n\t\t\t\tif (!canSwitch.length) return `pass`;\r\n\t\t\t\tconst target = this.chooseSwitch(\r\n\t\t\t\t\trequest.active,\r\n\t\t\t\t\tcanSwitch.map(slot => ({slot, pokemon: pokemon[slot - 1]}))\r\n\t\t\t\t);\r\n\t\t\t\tchosen.push(target);\r\n\t\t\t\treturn `switch ${target}`;\r\n\t\t\t});\r\n\r\n\t\t\tthis.choose(choices.join(`, `));\r\n\t\t} else if (request.active) {\r\n\t\t\t// move request\r\n\t\t\tlet [canMegaEvo, canUltraBurst, canZMove, canDynamax, canTerastallize] = [true, true, true, true, true];\r\n\t\t\tconst pokemon = request.side.pokemon;\r\n\t\t\tconst chosen: number[] = [];\r\n\t\t\tconst choices = request.active.map((active: AnyObject, i: number) => {\r\n\t\t\t\tif (pokemon[i].condition.endsWith(` fnt`) || pokemon[i].commanding) return `pass`;\r\n\r\n\t\t\t\tcanMegaEvo = canMegaEvo && active.canMegaEvo;\r\n\t\t\t\tcanUltraBurst = canUltraBurst && active.canUltraBurst;\r\n\t\t\t\tcanZMove = canZMove && !!active.canZMove;\r\n\t\t\t\tcanDynamax = canDynamax && !!active.canDynamax;\r\n\t\t\t\tcanTerastallize = canTerastallize && !!active.canTerastallize;\r\n\r\n\t\t\t\t// Determine whether we should change form if we do end up switching\r\n\t\t\t\tconst change = (canMegaEvo || canUltraBurst || canDynamax) && this.prng.next() < this.mega;\r\n\t\t\t\t// If we've already dynamaxed or if we're planning on potentially dynamaxing\r\n\t\t\t\t// we need to use the maxMoves instead of our regular moves\r\n\r\n\t\t\t\tconst useMaxMoves = (!active.canDynamax && active.maxMoves) || (change && canDynamax);\r\n\t\t\t\tconst possibleMoves = useMaxMoves ? active.maxMoves.maxMoves : active.moves;\r\n\r\n\t\t\t\tlet canMove = range(1, possibleMoves.length).filter(j => (\r\n\t\t\t\t\t// not disabled\r\n\t\t\t\t\t!possibleMoves[j - 1].disabled\r\n\t\t\t\t\t// NOTE: we don't actually check for whether we have PP or not because the\r\n\t\t\t\t\t// simulator will mark the move as disabled if there is zero PP and there are\r\n\t\t\t\t\t// situations where we actually need to use a move with 0 PP (Gen 1 Wrap).\r\n\t\t\t\t)).map(j => ({\r\n\t\t\t\t\tslot: j,\r\n\t\t\t\t\tmove: possibleMoves[j - 1].move,\r\n\t\t\t\t\ttarget: possibleMoves[j - 1].target,\r\n\t\t\t\t\tzMove: false,\r\n\t\t\t\t}));\r\n\t\t\t\tif (canZMove) {\r\n\t\t\t\t\tcanMove.push(...range(1, active.canZMove.length)\r\n\t\t\t\t\t\t.filter(j => active.canZMove[j - 1])\r\n\t\t\t\t\t\t.map(j => ({\r\n\t\t\t\t\t\t\tslot: j,\r\n\t\t\t\t\t\t\tmove: active.canZMove[j - 1].move,\r\n\t\t\t\t\t\t\ttarget: active.canZMove[j - 1].target,\r\n\t\t\t\t\t\t\tzMove: true,\r\n\t\t\t\t\t\t})));\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Filter out adjacentAlly moves if we have no allies left, unless they're our\r\n\t\t\t\t// only possible move options.\r\n\t\t\t\tconst hasAlly = pokemon.length > 1 && !pokemon[i ^ 1].condition.endsWith(` fnt`);\r\n\t\t\t\tconst filtered = canMove.filter(m => m.target !== `adjacentAlly` || hasAlly);\r\n\t\t\t\tcanMove = filtered.length ? filtered : canMove;\r\n\r\n\t\t\t\tconst moves = canMove.Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,2BAA2B;AAC3B,kBAA6B;AAV7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYO,MAAM,uBAAuB,kCAAa;AAAA,EAKhD,YACC,cACA,UAA0E,CAAC,GAC3E,QAAQ,OACP;AACD,UAAM,cAAc,KAAK;AACzB,S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;AAC1C,cAAI,KAAK,SAAS,QAAQ,GAAG;AAC5B,uBAAW;AACX,mBAAO;AAAA,UACR,WAAW,QAAQ;AAClB,gBAAI,iBAAiB;AACpB,gCAAkB;AAClB,qBAAO,GAAG;AAAA,YACX,WAAW,YAAY;AACtB,2BAAa;AACb,qBAAO,GAAG;AAAA,YACX,WAAW,YAAY;AACtB,2BAAa;AACb,qBAAO,GAAG;AAAA,YACX,OAAO;AACN,8BAAgB;AAChB,qBAAO,GAAG;AAAA,YACX;AAAA,UACD,OAAO;AACN,mBAAO;AAAA,UACR;AAAA,QACD,OAAO;AACN,gBAAM,IAAI,MAAM,GAAG,KAAK,YAAY,8BAA8B,eAAe,qBACpE,kBAAkB,qBAAqB,wBAAwB,sBAC9D,6BAA6B,kBAAkB;AAAA,QAC9D;AAAA,MACD,CAAC;AACD,WAAK,OAAO,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC/B,OAAO;AAEN,WAAK,OAAO,KAAK,kBAAkB,QAAQ,KAAK,OAAO,CAAC;AAAA,IACzD;AAAA,EACD;AAAA,EAEU,kBAAkB,MAA2B;AACtD,WAAO;AAAA,EACR;AAAA,EAEU,WAAW,QAAmB,OAAoD;AAC3F,WAAO,KAAK,KAAK,OAAO,KAAK,EAAE;AAAA,EAChC;AAAA,EAEU,aAAa,QAA+B,UAAwD;AAC7G,WAAO,KAAK,KAAK,OAAO,QAAQ,EAAE;AAAA,EACnC;AACD;AAGA,SAAS,MAAM,OAAe,KAAc,OAAO,GAAG;AACrD,MAAI,QAAQ,QAAW;AACtB,UAAM;AACN,YAAQ;AAAA,EACT;AACA,QAAM,SAAS,CAAC;AAChB,SAAO,SAAS,KAAK,SAAS,MAAM;AACnC,WAAO,KAAK,KAAK;AAAA,EAClB;AACA,SAAO;AACR;",
"names": []
}
+209
View File
@@ -0,0 +1,209 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var runner_exports = {};
__export(runner_exports, {
Runner: () => Runner
});
module.exports = __toCommonJS(runner_exports);
var import_assert = require("assert");
var fs = __toESM(require("fs"));
var import__ = require("..");
var import_battle = require("../battle");
var BattleStreams = __toESM(require("../battle-stream"));
var import_state = require("../state");
var import_prng = require("../prng");
var import_random_player_ai = require("./random-player-ai");
/**
* Battle Simulator runner.
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
const _Runner = class {
constructor(options) {
this.format = options.format;
this.prng = options.prng && !Array.isArray(options.prng) ? options.prng : new import_prng.PRNG(options.prng);
this.p1options = { ..._Runner.AI_OPTIONS, ...options.p1options };
this.p2options = { ..._Runner.AI_OPTIONS, ...options.p2options };
this.p3options = { ..._Runner.AI_OPTIONS, ...options.p3options };
this.p4options = { ..._Runner.AI_OPTIONS, ...options.p4options };
this.input = !!options.input;
this.output = !!options.output;
this.error = !!options.error;
this.dual = options.dual || false;
}
async run() {
const battleStream = this.dual ? new DualStream(this.input, this.dual === "debug") : new RawBattleStream(this.input);
const game = this.runGame(this.format, battleStream);
if (!this.error)
return game;
return game.catch((err) => {
console.log(`
${battleStream.rawInputLog.join("\n")}
`);
throw err;
});
}
async runGame(format, battleStream) {
const streams = BattleStreams.getPlayerStreams(battleStream);
const spec = { formatid: format, seed: this.prng.seed };
const is4P = import__.Dex.formats.get(format).gameType === "multi";
const p1spec = this.getPlayerSpec("Bot 1", this.p1options);
const p2spec = this.getPlayerSpec("Bot 2", this.p2options);
let p3spec, p4spec;
if (is4P) {
p3spec = this.getPlayerSpec("Bot 3", this.p3options);
p4spec = this.getPlayerSpec("Bot 4", this.p4options);
}
const p1 = this.p1options.createAI(
streams.p1,
{ seed: this.newSeed(), ...this.p1options }
);
const p2 = this.p2options.createAI(
streams.p2,
{ seed: this.newSeed(), ...this.p2options }
);
let p3, p4;
if (is4P) {
p3 = this.p4options.createAI(
streams.p3,
{ seed: this.newSeed(), ...this.p3options }
);
p4 = this.p4options.createAI(
streams.p4,
{ seed: this.newSeed(), ...this.p4options }
);
}
void p1.start();
void p2.start();
if (is4P) {
void p3.start();
void p4.start();
}
let initMessage = `>start ${JSON.stringify(spec)}
>player p1 ${JSON.stringify(p1spec)}
>player p2 ${JSON.stringify(p2spec)}`;
if (is4P) {
initMessage += `
>player p3 ${JSON.stringify(p3spec)}
>player p4 ${JSON.stringify(p4spec)}`;
}
void streams.omniscient.write(initMessage);
for await (const chunk of streams.omniscient) {
if (this.output)
console.log(chunk);
}
return streams.omniscient.writeEnd();
}
// Same as PRNG#generatedSeed, only deterministic.
// NOTE: advances this.prng's seed by 4.
newSeed() {
return [
Math.floor(this.prng.next() * 65536),
Math.floor(this.prng.next() * 65536),
Math.floor(this.prng.next() * 65536),
Math.floor(this.prng.next() * 65536)
];
}
getPlayerSpec(name, options) {
if (options.team)
return { name, team: options.team };
return { name, seed: this.newSeed() };
}
};
let Runner = _Runner;
Runner.AI_OPTIONS = {
createAI: (s, o) => new import_random_player_ai.RandomPlayerAI(s, o),
move: 0.7,
mega: 0.6
};
class RawBattleStream extends BattleStreams.BattleStream {
constructor(input) {
super();
this.input = !!input;
this.rawInputLog = [];
}
_write(message) {
if (this.input)
console.log(message);
this.rawInputLog.push(message);
super._write(message);
}
}
class DualStream {
constructor(input, debug) {
this.debug = debug;
this.control = new RawBattleStream(input);
this.test = new RawBattleStream(false);
}
get rawInputLog() {
const control = this.control.rawInputLog;
const test = this.test.rawInputLog;
import_assert.strict.deepEqual(test, control);
return control;
}
async read() {
const control = await this.control.read();
const test = await this.test.read();
if (!this.debug)
import_assert.strict.equal(import_state.State.normalizeLog(test), import_state.State.normalizeLog(control));
return control;
}
write(message) {
this.control._write(message);
this.test._write(message);
this.compare();
}
writeEnd() {
this.compare(true);
this.control._writeEnd();
this.test._writeEnd();
}
compare(end) {
if (!this.control.battle || !this.test.battle)
return;
const control = this.control.battle.toJSON();
const test = this.test.battle.toJSON();
try {
import_assert.strict.deepEqual(import_state.State.normalize(test), import_state.State.normalize(control));
} catch (err) {
if (this.debug) {
fs.writeFileSync("logs/control.json", JSON.stringify(control, null, 2));
fs.writeFileSync("logs/test.json", JSON.stringify(test, null, 2));
}
throw new Error(err.message);
}
if (end)
return;
const send = this.test.battle.send;
this.test.battle = import_battle.Battle.fromJSON(test);
this.test.battle.restart(send);
}
}
//# sourceMappingURL=runner.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../sim/tools/runner.ts"],
"sourcesContent": ["/**\r\n * Battle Simulator runner.\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {strict as assert} from 'assert';\r\nimport * as fs from 'fs';\r\n\r\nimport {Dex} from '..';\r\nimport {ObjectReadWriteStream} from '../../lib/streams';\r\nimport {Battle} from '../battle';\r\nimport * as BattleStreams from '../battle-stream';\r\nimport {State} from '../state';\r\nimport {PRNG, PRNGSeed} from '../prng';\r\nimport {RandomPlayerAI} from './random-player-ai';\r\n\r\nexport interface AIOptions {\r\n\tcreateAI: (stream: ObjectReadWriteStream<string>, options: AIOptions) => RandomPlayerAI;\r\n\tmove?: number;\r\n\tmega?: number;\r\n\tseed?: PRNG | PRNGSeed | null;\r\n\tteam?: PokemonSet[];\r\n}\r\n\r\nexport interface RunnerOptions {\r\n\tformat: string;\r\n\tprng?: PRNG | PRNGSeed | null;\r\n\tp1options?: AIOptions;\r\n\tp2options?: AIOptions;\r\n\tp3options?: AIOptions;\r\n\tp4options?: AIOptions;\r\n\tinput?: boolean;\r\n\toutput?: boolean;\r\n\terror?: boolean;\r\n\tdual?: boolean | 'debug';\r\n}\r\n\r\nexport class Runner {\r\n\tstatic readonly AI_OPTIONS: AIOptions = {\r\n\t\tcreateAI: (s: ObjectReadWriteStream<string>, o: AIOptions) => new RandomPlayerAI(s, o),\r\n\t\tmove: 0.7,\r\n\t\tmega: 0.6,\r\n\t};\r\n\r\n\tprivate readonly prng: PRNG;\r\n\tprivate readonly p1options: AIOptions;\r\n\tprivate readonly p2options: AIOptions;\r\n\tprivate readonly p3options: AIOptions;\r\n\tprivate readonly p4options: AIOptions;\r\n\tprivate readonly format: string;\r\n\tprivate readonly input: boolean;\r\n\tprivate readonly output: boolean;\r\n\tprivate readonly error: boolean;\r\n\tprivate readonly dual: boolean | 'debug';\r\n\r\n\tconstructor(options: RunnerOptions) {\r\n\t\tthis.format = options.format;\r\n\r\n\t\tthis.prng = (options.prng && !Array.isArray(options.prng)) ?\r\n\t\t\toptions.prng : new PRNG(options.prng);\r\n\t\tthis.p1options = {...Runner.AI_OPTIONS, ...options.p1options};\r\n\t\tthis.p2options = {...Runner.AI_OPTIONS, ...options.p2options};\r\n\t\tthis.p3options = {...Runner.AI_OPTIONS, ...options.p3options};\r\n\t\tthis.p4options = {...Runner.AI_OPTIONS, ...options.p4options};\r\n\r\n\t\tthis.input = !!options.input;\r\n\t\tthis.output = !!options.output;\r\n\t\tthis.error = !!options.error;\r\n\t\tthis.dual = options.dual || false;\r\n\t}\r\n\r\n\tasync run() {\r\n\t\tconst battleStream = this.dual ?\r\n\t\t\tnew DualStream(this.input, this.dual === 'debug') :\r\n\t\t\tnew RawBattleStream(this.input);\r\n\t\tconst game = this.runGame(this.format, battleStream);\r\n\t\tif (!this.error) return game;\r\n\t\treturn game.catch(err => {\r\n\t\t\tconsole.log(`\\n${battleStream.rawInputLog.join('\\n')}\\n`);\r\n\t\t\tthrow err;\r\n\t\t});\r\n\t}\r\n\r\n\tprivate async runGame(format: string, battleStream: RawBattleStream | DualStream) {\r\n\t\t// @ts-ignore - DualStream implements everything relevant from BattleStream.\r\n\t\tconst streams = BattleStreams.getPlayerStreams(battleStream);\r\n\t\tconst spec = {formatid: format, seed: this.prng.seed};\r\n\t\tconst is4P = Dex.formats.get(format).gameType === 'multi';\r\n\t\tconst p1spec = this.getPlayerSpec(\"Bot 1\", this.p1options);\r\n\t\tconst p2spec = this.getPlayerSpec(\"Bot 2\", this.p2options);\r\n\t\tlet p3spec: typeof p1spec, p4spec: typeof p1spec;\r\n\t\tif (is4P) {\r\n\t\t\tp3spec = this.getPlayerSpec(\"Bot 3\", this.p3options);\r\n\t\t\tp4spec = this.getPlayerSpec(\"Bot 4\", this.p4options);\r\n\t\t}\r\n\r\n\t\tconst p1 = this.p1options.createAI(\r\n\t\t\tstreams.p1, {seed: this.newSeed(), ...this.p1options}\r\n\t\t);\r\n\t\tconst p2 = this.p2options.createAI(\r\n\t\t\tstreams.p2, {seed: this.newSeed(), ...this.p2options}\r\n\t\t);\r\n\t\tlet p3: RandomPlayerAI, p4: RandomPlayerAI;\r\n\t\tif (is4P) {\r\n\t\t\tp3 = this.p4options.createAI(\r\n\t\t\t\tstreams.p3, {seed: this.newSeed(), ...this.p3options}\r\n\t\t\t);\r\n\t\t\tp4 = this.p4options.createAI(\r\n\t\t\t\tstreams.p4, {seed: this.newSeed(), ...this.p4options}\r\n\t\t\t);\r\n\t\t}\r\n\t\t// TODO: Use `await Promise.race([streams.omniscient.read(), p1, p2])` to avoid\r\n\t\t// leaving these promises dangling once it no longer causes memory leaks (v8#9069).\r\n\t\tvoid p1.start();\r\n\t\tvoid p2.start();\r\n\t\tif (is4P) {\r\n\t\t\tvoid p3!.start();\r\n\t\t\tvoid p4!.start();\r\n\t\t}\r\n\r\n\t\tlet initMessage = `>start ${JSON.stringify(spec)}\\n` +\r\n\t\t`>player p1 ${JSON.stringify(p1spec)}\\n` +\r\n\t\t`>player p2 ${JSON.stringify(p2spec)}`;\r\n\t\tif (is4P) {\r\n\t\t\tinitMessage += `\\n` +\r\n\t\t\t`>player p3 ${JSON.stringify(p3spec!)}\\n` +\r\n\t\t\t`>player p4 ${JSON.stringify(p4spec!)}`;\r\n\t\t}\r\n\t\tvoid streams.omniscient.write(initMessage);\r\n\r\n\t\tfor await (const chunk of streams.omniscient) {\r\n\t\t\tif (this.output) console.log(chunk);\r\n\t\t}\r\n\t\treturn streams.omniscient.writeEnd();\r\n\t}\r\n\r\n\t// Same as PRNG#generatedSeed, only deterministic.\r\n\t// NOTE: advances this.prng's seed by Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,oBAA+B;AAC/B,SAAoB;AAEpB,eAAkB;AAElB,oBAAqB;AACrB,oBAA+B;AAC/B,mBAAoB;AACpB,kBAA6B;AAC7B,8BAA6B;AAhB7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCO,MAAM,UAAN,MAAa;AAAA,EAkBnB,YAAY,SAAwB;AACnC,SAAK,SAAS,QAAQ;AAEtB,SAAK,OAAQ,QAAQ,QAAQ,CAAC,MAAM,QAAQ,QAAQ,IAAI,IACvD,QAAQ,OAAO,IAAI,iBAAK,QAAQ,IAAI;AACrC,SAAK,YAAY,EAAC,GAAG,QAAO,YAAY,GAAG,QAAQ,UAAS;AAC5D,SAAK,YAAY,EAAC,GAAG,QAAO,YAAY,GAAG,QAAQ,UAAS;AAC5D,SAAK,YAAY,EAAC,GAAG,QAAO,YAAY,GAAG,QAAQ,UAAS;AAC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