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

File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/battle-actions.ts"],
"sourcesContent": ["import {Dex, toID} from './dex';\r\n\r\nconst CHOOSABLE_TARGETS = new Set(['normal', 'any', 'adjacentAlly', 'adjacentAllyOrSelf', 'adjacentFoe']);\r\n\r\nexport class BattleActions {\r\n\tbattle: Battle;\r\n\tdex: ModdedDex;\r\n\r\n\treadonly MAX_MOVES: {readonly [k: string]: string} = {\r\n\t\tFlying: 'Max Airstream',\r\n\t\tDark: 'Max Darkness',\r\n\t\tFire: 'Max Flare',\r\n\t\tBug: 'Max Flutterby',\r\n\t\tWater: 'Max Geyser',\r\n\t\tStatus: 'Max Guard',\r\n\t\tIce: 'Max Hailstorm',\r\n\t\tFighting: 'Max Knuckle',\r\n\t\tElectric: 'Max Lightning',\r\n\t\tPsychic: 'Max Mindstorm',\r\n\t\tPoison: 'Max Ooze',\r\n\t\tGrass: 'Max Overgrowth',\r\n\t\tGhost: 'Max Phantasm',\r\n\t\tGround: 'Max Quake',\r\n\t\tRock: 'Max Rockfall',\r\n\t\tFairy: 'Max Starfall',\r\n\t\tSteel: 'Max Steelspike',\r\n\t\tNormal: 'Max Strike',\r\n\t\tDragon: 'Max Wyrmwind',\r\n\t};\r\n\r\n\treadonly Z_MOVES: {readonly [k: string]: string} = {\r\n\t\tPoison: \"Acid Downpour\",\r\n\t\tFighting: \"All-Out Pummeling\",\r\n\t\tDark: \"Black Hole Eclipse\",\r\n\t\tGrass: \"Bloom Doom\",\r\n\t\tNormal: \"Breakneck Blitz\",\r\n\t\tRock: \"Continental Crush\",\r\n\t\tSteel: \"Corkscrew Crash\",\r\n\t\tDragon: \"Devastating Drake\",\r\n\t\tElectric: \"Gigavolt Havoc\",\r\n\t\tWater: \"Hydro Vortex\",\r\n\t\tFire: \"Inferno Overdrive\",\r\n\t\tGhost: \"Never-Ending Nightmare\",\r\n\t\tBug: \"Savage Spin-Out\",\r\n\t\tPsychic: \"Shattered Psyche\",\r\n\t\tIce: \"Subzero Slammer\",\r\n\t\tFlying: \"Supersonic Skystrike\",\r\n\t\tGround: \"Tectonic Rage\",\r\n\t\tFairy: \"Twinkle Tackle\",\r\n\t};\r\n\r\n\tconstructor(battle: Battle) {\r\n\t\tthis.battle = battle;\r\n\t\tthis.dex = battle.dex;\r\n\t\tif (this.dex.data.Scripts.actions) Object.assign(this, this.dex.data.Scripts.actions);\r\n\t\tif (battle.format.actions) Object.assign(this, battle.format.actions);\r\n\t}\r\n\r\n\t// #region SWITCH\r\n\t// ==================================================================\r\n\r\n\tswitchIn(pokemon: Pokemon, pos: number, sourceEffect: Effect | null = null, isDrag?: boolean) {\r\n\t\tif (!pokemon || pokemon.isActive) {\r\n\t\t\tthis.battle.hint(\"A switch failed because the Pok\u00E9mon trying to switch in is already in.\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tconst side = pokemon.side;\r\n\t\tif (pos >= side.active.length) {\r\n\t\t\tthrow new Error(`Invalid switch position ${pos} / ${side.active.length}`);\r\n\t\t}\r\n\t\tconst oldActive = side.active[pos];\r\n\t\tconst unfaintedActive = oldActive?.hp ? oldActive : null;\r\n\t\tif (unfaintedActive) {\r\n\t\t\toldActive.beingCalledBack = true;\r\n\t\t\tlet switchCopyFlag: 'copyvolatile' | 'shedtail' | boolean = false;\r\n\t\t\tif (sourceEffect && typeof (sourceEffect as Move).selfSwitch === 'string') {\r\n\t\t\t\tswitchCopyFlag = (sourceEffect as Move).selfSwitch!;\r\n\t\t\t}\r\n\t\t\tif (!oldActive.skipBeforeSwitchOutEventFlag && !isDrag) {\r\n\t\t\t\tthis.battle.runEvent('BeforeSwitchOut', oldActive);\r\n\t\t\t\tif (this.battle.gen >= 5) {\r\n\t\t\t\t\tthis.battle.eachEvent('Update');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\toldActive.skipBeforeSwitchOutEventFlag = false;\r\n\t\t\tif (!this.battle.runEvent('SwitchOut', oldActive)) {\r\n\t\t\t\t// Warning: DO NOT interrupt a switch-out if you just want to trap a pokemon.\r\n\t\t\t\t// To trap a pokemon and prevent it from switching out, (e.g. Mean Look, Magnet Pull)\r\n\t\t\t\t// use the 'trapped' flag instead.\r\n\r\n\t\t\t\t// Note: Nothing in the real games can interrupt a switch-out (except Pursuit KOing,\r\n\t\t\t\t// which is handled elsewhere); this is just for custom formats.\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tif (!oldActive.hp) {\r\n\t\t\t\t// a pokemon fainted from Pursuit before it could switch\r\n\t\t\t\treturn 'pursuitfaint';\r\n\t\t\t}\r\n\r\n\t\t\t// will definitely switch out at this point\r\n\r\n\t\t\toldActive.illusion = null;\r\n\t\t\tthis.battle.singleEvent('End', oldActive.getAbility(), oldActive.abilityState, oldActive);\r\n\r\n\t\t\t// if a pokemon is forced out by Whirlwind/etc or Eject Button/Pack, it can't use its chosen move\r\n\t\t\tthis.battle.queue.cancelAction(oldActive);\r\n\r\n\t\t\tlet newMove = null;\r\n\t\t\tif (this.battle.gen === 4 && sourceEffect) {\r\n\t\t\t\tnewMove = oldActive.lastMove;\r\n\t\t\t}\r\n\t\t\tif (switchCopyFlag) {\r\n\t\t\t\tpokemon.copyVolatileFrom(oldActive, switchCopyFlag);\r\n\t\t\t}\r\n\t\t\tif (newMove) pokemon.lastMove = newMove;\r\n\t\t\toldActive.clearVolatile();\r\n\t\t}\r\n\t\tif (oldActive) {\r\n\t\t\toldActive.isActive = false;\r\n\t\t\toldActive.isStarted = false;\r\n\t\t\toldActive.usedItemThisTurn = false;\r\n\t\t\toldActive.statsRaisedThisTurn = false;\r\n\t\t\toldActive.statsLoweredThisTurn = false;\r\n\t\t\toldActive.position = pokemon.position;\r\n\t\t\tpokemon.position = pos;\r\n\t\t\tside.pokemon[pokemon.position] = pokemon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AACR,QAAI,SAAS,KAAK,OAAO,UAAU,SAAS,WAAW,SAAS,gBAAgB,WAAW,cAAc;AACzG,QAAI,WAAW,KAAK,IAAI,cAAc,cAAc;AACpD,UAAM,mBAAmB,SAAS;AAClC,QAAI,SAAS,OAAO,cAAc,CAAC,SAAS,CAAC,WAAW,CAAC,cAAc;AACtE,YAAM,cAAc,KAAK,OAAO,SAAS,kBAAkB,SAAS,QAAQ,QAAQ;AACpF,UAAI,eAAe,gBAAgB,MAAM;AACxC,mBAAW,KAAK,IAAI,cAAc,WAAW;AAC7C,YAAI;AAAkB,mBAAS,mBAAmB;AAClD,iBAAS,KAAK,OAAO,gBAAgB,SAAS,QAAQ;AAAA,MACvD;AAAA,IACD;AACA,QAAI,OAAO;AACX,QAAI,OAAO;AACV,aAAO,KAAK,eAAe,UAAU,OAAO;AAAA,IAC7C,WAAW,SAAS;AACnB,aAAO,KAAK,iBAAiB,UAAU,OAAO;AAAA,IAC/C;AAEA,SAAK,aAAa;AAElB,SAAK,OAAO,cAAc,MAAM,SAAS,MAAM;AAU/C,UAAM,cAAc,KAAK,OAAO,SAAS,cAAc,SAAS,QAAQ,IAAI;AAC5E,QAAI,CAAC,aAAa;AACjB,WAAK,OAAO,SAAS,eAAe,SAAS,QAAQ,IAAI;AACzD,WAAK,OAAO,gBAAgB,IAAI;AAIhC,cAAQ,qBAAqB;AAC7B;AAAA,IACD;AACA,QAAI,KAAK,oBAAoB;AAC5B,UAAI,KAAK,mBAAmB,KAAK,KAAK,QAAQ,SAAS,QAAQ,IAAI,GAAG;AACrE,aAAK,OAAO,gBAAgB,IAAI;AAChC,gBAAQ,qBAAqB;AAC7B;AAAA,MACD;AAAA,IACD;AACA,YAAQ,aAAa;AALine truncated
"names": ["target", "zMove", "basePower"]
}
+309
View File
@@ -0,0 +1,309 @@
"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 battle_queue_exports = {};
__export(battle_queue_exports, {
BattleQueue: () => BattleQueue,
default: () => battle_queue_default
});
module.exports = __toCommonJS(battle_queue_exports);
/**
* Simulator Battle Action Queue
* Pokemon Showdown - http://pokemonshowdown.com/
*
* The action queue is the core of the battle simulation. A rough overview of
* the core battle loop:
*
* - chosen moves/switches are added to the action queue
* - the action queue is sorted in speed/priority order
* - we go through the action queue
* - repeat
*
* @license MIT
*/
class BattleQueue {
constructor(battle) {
this.battle = battle;
this.list = [];
const queueScripts = battle.format.queue || battle.dex.data.Scripts.queue;
if (queueScripts)
Object.assign(this, queueScripts);
}
shift() {
return this.list.shift();
}
peek(end) {
return this.list[end ? this.list.length - 1 : 0];
}
push(action) {
return this.list.push(action);
}
unshift(action) {
return this.list.unshift(action);
}
// eslint-disable-next-line no-restricted-globals
[Symbol.iterator]() {
return this.list[Symbol.iterator]();
}
entries() {
return this.list.entries();
}
/**
* Takes an ActionChoice, and fills it out into a full Action object.
*
* Returns an array of Actions because some ActionChoices (like mega moves)
* resolve to two Actions (mega evolution + use move)
*/
resolveAction(action, midTurn = false) {
if (!action)
throw new Error(`Action not passed to resolveAction`);
if (action.choice === "pass")
return [];
const actions = [action];
if (!action.side && action.pokemon)
action.side = action.pokemon.side;
if (!action.move && action.moveid)
action.move = this.battle.dex.getActiveMove(action.moveid);
if (!action.order) {
const orders = {
team: 1,
start: 2,
instaswitch: 3,
beforeTurn: 4,
beforeTurnMove: 5,
revivalblessing: 6,
runUnnerve: 100,
runSwitch: 101,
runPrimal: 102,
switch: 103,
megaEvo: 104,
runDynamax: 105,
terastallize: 106,
priorityChargeMove: 107,
shift: 200,
// default is 200 (for moves)
residual: 300
};
if (action.choice in orders) {
action.order = orders[action.choice];
} else {
action.order = 200;
if (!["move", "event"].includes(action.choice)) {
throw new Error(`Unexpected orderless action ${action.choice}`);
}
}
}
if (!midTurn) {
if (action.choice === "move") {
if (!action.maxMove && !action.zmove && action.move.beforeTurnCallback) {
actions.unshift(...this.resolveAction({
choice: "beforeTurnMove",
pokemon: action.pokemon,
move: action.move,
targetLoc: action.targetLoc
}));
}
if (action.mega && !action.pokemon.isSkyDropped()) {
actions.unshift(...this.resolveAction({
choice: "megaEvo",
pokemon: action.pokemon
}));
}
if (action.terastallize && !action.pokemon.terastallized) {
actions.unshift(...this.resolveAction({
choice: "terastallize",
pokemon: action.pokemon
}));
}
if (action.maxMove && !action.pokemon.volatiles["dynamax"]) {
actions.unshift(...this.resolveAction({
choice: "runDynamax",
pokemon: action.pokemon
}));
}
if (!action.maxMove && !action.zmove && action.move.priorityChargeCallback) {
actions.unshift(...this.resolveAction({
choice: "priorityChargeMove",
pokemon: action.pokemon,
move: action.move
}));
}
action.fractionalPriority = this.battle.runEvent("FractionalPriority", action.pokemon, null, action.move, 0);
} else if (["switch", "instaswitch"].includes(action.choice)) {
if (typeof action.pokemon.switchFlag === "string") {
action.sourceEffect = this.battle.dex.moves.get(action.pokemon.switchFlag);
}
action.pokemon.switchFlag = false;
}
}
const deferPriority = this.battle.gen === 7 && action.mega && action.mega !== "done";
if (action.move) {
let target = null;
action.move = this.battle.dex.getActiveMove(action.move);
if (!action.targetLoc) {
target = this.battle.getRandomTarget(action.pokemon, action.move);
if (target)
action.targetLoc = action.pokemon.getLocOf(target);
}
action.originalTarget = action.pokemon.getAtLoc(action.targetLoc);
}
if (!deferPriority)
this.battle.getActionSpeed(action);
return actions;
}
/**
* Makes the passed action happen next (skipping speed order).
*/
prioritizeAction(action, sourceEffect) {
for (const [i, curAction] of this.list.entries()) {
if (curAction === action) {
this.list.splice(i, 1);
break;
}
}
action.sourceEffect = sourceEffect;
action.order = 3;
this.list.unshift(action);
}
/**
* Changes a pokemon's action, and inserts its new action
* in priority order.
*
* You'd normally want the OverrideAction event (which doesn't
* change priority order).
*/
changeAction(pokemon, action) {
this.cancelAction(pokemon);
if (!action.pokemon)
action.pokemon = pokemon;
this.insertChoice(action);
}
addChoice(choices) {
if (!Array.isArray(choices))
choices = [choices];
for (const choice of choices) {
const resolvedChoices = this.resolveAction(choice);
this.list.push(...resolvedChoices);
for (const resolvedChoice of resolvedChoices) {
if (resolvedChoice && resolvedChoice.choice === "move" && resolvedChoice.move.id !== "recharge") {
resolvedChoice.pokemon.side.lastSelectedMove = resolvedChoice.move.id;
}
}
}
}
willAct() {
for (const action of this.list) {
if (["move", "switch", "instaswitch", "shift"].includes(action.choice)) {
return action;
}
}
return null;
}
willMove(pokemon) {
if (pokemon.fainted)
return null;
for (const action of this.list) {
if (action.choice === "move" && action.pokemon === pokemon) {
return action;
}
}
return null;
}
cancelAction(pokemon) {
const oldLength = this.list.length;
for (let i = 0; i < this.list.length; i++) {
if (this.list[i].pokemon === pokemon) {
this.list.splice(i, 1);
i--;
}
}
return this.list.length !== oldLength;
}
cancelMove(pokemon) {
for (const [i, action] of this.list.entries()) {
if (action.choice === "move" && action.pokemon === pokemon) {
this.list.splice(i, 1);
return true;
}
}
return false;
}
willSwitch(pokemon) {
for (const action of this.list) {
if (["switch", "instaswitch"].includes(action.choice) && action.pokemon === pokemon) {
return action;
}
}
return null;
}
/**
* Inserts the passed action into the action queue when it normally
* would have happened (sorting by priority/speed), without
* re-sorting the existing actions.
*/
insertChoice(choices, midTurn = false) {
if (Array.isArray(choices)) {
for (const choice2 of choices) {
this.insertChoice(choice2);
}
return;
}
const choice = choices;
if (choice.pokemon) {
choice.pokemon.updateSpeed();
}
const actions = this.resolveAction(choice, midTurn);
let firstIndex = null;
let lastIndex = null;
for (const [i, curAction] of this.list.entries()) {
const compared = this.battle.comparePriority(actions[0], curAction);
if (compared <= 0 && firstIndex === null) {
firstIndex = i;
}
if (compared < 0) {
lastIndex = i;
break;
}
}
if (firstIndex === null) {
this.list.push(...actions);
} else {
if (lastIndex === null)
lastIndex = this.list.length;
const index = firstIndex === lastIndex ? firstIndex : this.battle.random(firstIndex, lastIndex + 1);
this.list.splice(index, 0, ...actions);
}
}
clear() {
this.list = [];
}
debug(action) {
if (action) {
return `${action.order || ""}:${action.priority || ""}:${action.speed || ""}:${action.subOrder || ""} - ${action.choice}${action.pokemon ? " " + action.pokemon : ""}${action.move ? " " + action.move : ""}`;
}
return this.list.map(
(queueAction) => this.debug(queueAction)
).join("\n") + "\n";
}
sort() {
this.battle.speedSort(this.list);
return this;
}
}
var battle_queue_default = BattleQueue;
//# sourceMappingURL=battle-queue.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/battle-queue.ts"],
"sourcesContent": ["/**\r\n * Simulator Battle Action Queue\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * The action queue is the core of the battle simulation. A rough overview of\r\n * the core battle loop:\r\n *\r\n * - chosen moves/switches are added to the action queue\r\n * - the action queue is sorted in speed/priority order\r\n * - we go through the action queue\r\n * - repeat\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport type {Battle} from './battle';\r\n\r\n/** A move action */\r\nexport interface MoveAction {\r\n\t/** action type */\r\n\tchoice: 'move' | 'beforeTurnMove' | 'priorityChargeMove';\r\n\torder: 3 | 5 | 200 | 201 | 199 | 106;\r\n\t/** priority of the action (lower first) */\r\n\tpriority: number;\r\n\t/** fractional priority of the action (lower first) */\r\n\tfractionalPriority: number;\r\n\t/** speed of pokemon using move (higher first if priority tie) */\r\n\tspeed: number;\r\n\t/** the pokemon doing the move */\r\n\tpokemon: Pokemon;\r\n\t/** location of the target, relative to pokemon's side */\r\n\ttargetLoc: number;\r\n\t/** original target pokemon, for target-tracking moves */\r\n\toriginalTarget: Pokemon;\r\n\t/** a move to use (move action only) */\r\n\tmoveid: ID;\r\n\t/** a move to use (move action only) */\r\n\tmove: Move;\r\n\t/** true if megaing or ultra bursting */\r\n\tmega: boolean | 'done';\r\n\t/** if zmoving, the name of the zmove */\r\n\tzmove?: string;\r\n\t/** if dynamaxed, the name of the max move */\r\n\tmaxMove?: string;\r\n\t/** effect that called the move (eg Instruct) if any */\r\n\tsourceEffect?: Effect | null;\r\n}\r\n\r\n/** A switch action */\r\nexport interface SwitchAction {\r\n\t/** action type */\r\n\tchoice: 'switch' | 'instaswitch' | 'revivalblessing';\r\n\torder: 3 | 6 | 103;\r\n\t/** priority of the action (lower first) */\r\n\tpriority: number;\r\n\t/** speed of pokemon switching (higher first if priority tie) */\r\n\tspeed: number;\r\n\t/** the pokemon doing the switch */\r\n\tpokemon: Pokemon;\r\n\t/** pokemon to switch to */\r\n\ttarget: Pokemon;\r\n\t/** effect that called the switch (eg U */\r\n\tsourceEffect: Effect | null;\r\n}\r\n\r\n/** A Team Preview choice action */\r\nexport interface TeamAction {\r\n\t/** action type */\r\n\tchoice: 'team';\r\n\t/** priority of the action (lower first) */\r\n\tpriority: number;\r\n\t/** unused for this action type */\r\n\tspeed: 1;\r\n\t/** the pokemon switching */\r\n\tpokemon: Pokemon;\r\n\t/** new index */\r\n\tindex: number;\r\n}\r\n\r\n/** A generic action not done by a pokemon */\r\nexport interface FieldAction {\r\n\t/** action type */\r\n\tchoice: 'start' | 'residual' | 'pass' | 'beforeTurn';\r\n\t/** priority of the action (lower first) */\r\n\tpriority: number;\r\n\t/** unused for this action type */\r\n\tspeed: 1;\r\n\t/** unused for this action type */\r\n\tpokemon: null;\r\n}\r\n\r\n/** A generic action done by a single pokemon */\r\nexport interface PokemonAction {\r\n\t/** action type */\r\n\tchoice: 'megaEvo' | 'shift' | 'runPrimal' | 'runSwitch' | 'event' | 'runUnnerve' | 'runDynamax' | 'terastallize';\r\n\t/** priority of the action (lower first) */\r\n\tpriority: number;\r\n\t/** speed of pokemon doing action (higher first if priority tie) */\r\n\tspeed: number;\r\n\t/** the pokemon doing action */\r\n\tpokemon: Pokemon;\r\n\t/** `runSwitch` only: the pokemon forcing this pokemon to switch in */\r\n\tdragger?: Pokemon;\r\n\t/** `event` only: the event to run */\r\n\tevent?: string;\r\n}\r\n\r\nexport type Action = MoveAction | SwitchAction | TeamAction | FieldAction | PokemonAction;\r\n\r\n/**\r\n * An ActionChoice is like an Action and has the same structure, but it doesn't need to be fully filled out.\r\n *\r\n * Any Action or ChosenAction qualifies as an ActionChoice.\r\n *\r\n * The `[k: string]: any` part is required so TypeScript won't warn about unnecessary properties.\r\n */\r\nexport interface ActionChoice {\r\n\tchoice: string;\r\n\t[k: string]: any;\r\n}\r\n\r\n/**\r\n * Kind of like a priority queue, although not sorted mid-turn in Gen 1-7.\r\n *\r\n * Sort order is documented in `BattleQueue.comparePriority`.\r\n */\r\nexport class BattleQueue {\r\n\tbattle: Battle;\r\n\tlist: Action[];\r\n\tconstructor(battle: Battle) {\r\n\t\tthis.battle = battle;\r\n\t\tthis.list = [];\r\n\t\tconst queueScripts = battle.format.queue || battle.dex.data.Scripts.queue;\r\n\t\tif (queueScripts) Object.assign(this, queueScripts);\r\n\t}\r\n\r\n\tshift() {\r\n\t\treturn this.list.shift();\r\n\t}\r\n\tpeek(end?: boolean): Action | undefined {\r\n\t\treturn this.list[end ? this.list.length - 1 : 0];\r\n\t}\r\n\tpush(action: Action) {\r\n\t\treturn this.list.push(action);\r\n\t}\r\n\tunshift(action: Action) {\r\n\t\treturn this.list.unshift(action);\r\n\t}\r\n\t// eslint-disable-next-line no-restricted-globals\r\n\t[Symbol.iterator]() { return this.list[Symbol.iterator](); }\r\n\tentries() {\r\n\t\treturn this.list.entries();\r\n\t}\r\n\r\n\t/**\r\n\t * Takes an ActiLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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KAAK,WAAW;AAAA,EAC7B;AAAA,EAEA,WAAW,SAAkB;AAC5B,eAAW,CAAC,GAAG,MAAM,KAAK,KAAK,KAAK,QAAQ,GAAG;AAC9C,UAAI,OAAO,WAAW,UAAU,OAAO,YAAY,SAAS;AAC3D,aAAK,KAAK,OAAO,GAAG,CAAC;AACrB,eAAO;AAAA,MACR;AAAA,IACD;AACA,WAAO;AAAA,EACR;AAAA,EAEA,WAAW,SAAkB;AAC5B,eAAW,UAAU,KAAK,MAAM;AAC/B,UAAI,CAAC,UAAU,aAAa,EAAE,SAAS,OAAO,MAAM,KAAK,OAAO,YAAY,SAAS;AACpF,eAAO;AAAA,MACR;AAAA,IACD;AACA,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,SAAwC,UAAU,OAAO;AACrE,QAAI,MAAM,QAAQ,OAAO,GAAG;AAC3B,iBAAWA,WAAU,SAAS;AAC7B,aAAK,aAAaA,OAAM;AAAA,MACzB;AACA;AAAA,IACD;AACA,UAAM,SAAS;AAEf,QAAI,OAAO,SAAS;AACnB,aAAO,QAAQ,YAAY;AAAA,IAC5B;AACA,UAAM,UAAU,KAAK,cAAc,QAAQ,OAAO;AAElD,QAAI,aAAa;AACjB,QAAI,YAAY;AAChB,eAAW,CAAC,GAAG,SAAS,KAAK,KAAK,KAAK,QAAQ,GAAG;AACjD,YAAM,WAAW,KAAKLine truncated
"names": ["choice"]
}
+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 battle_stream_exports = {};
__export(battle_stream_exports, {
BattlePlayer: () => BattlePlayer,
BattleStream: () => BattleStream,
BattleTextStream: () => BattleTextStream,
getPlayerStreams: () => getPlayerStreams
});
module.exports = __toCommonJS(battle_stream_exports);
var import_lib = require("../lib");
var import_teams = require("./teams");
var import_battle = require("./battle");
/**
* Battle Stream
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Supports interacting with a PS battle in Stream format.
*
* This format is VERY NOT FINALIZED, please do not use it directly yet.
*
* @license MIT
*/
function splitFirst(str, delimiter, limit = 1) {
const splitStr = [];
while (splitStr.length < limit) {
const delimiterIndex = str.indexOf(delimiter);
if (delimiterIndex >= 0) {
splitStr.push(str.slice(0, delimiterIndex));
str = str.slice(delimiterIndex + delimiter.length);
} else {
splitStr.push(str);
str = "";
}
}
splitStr.push(str);
return splitStr;
}
class BattleStream extends import_lib.Streams.ObjectReadWriteStream {
constructor(options2 = {}) {
super();
this.debug = !!options2.debug;
this.noCatch = !!options2.noCatch;
this.replay = options2.replay || false;
this.keepAlive = !!options2.keepAlive;
this.battle = null;
}
_write(chunk) {
if (this.noCatch) {
this._writeLines(chunk);
} else {
try {
this._writeLines(chunk);
} catch (err) {
this.pushError(err, true);
return;
}
}
if (this.battle)
this.battle.sendUpdates();
}
_writeLines(chunk) {
for (const line of chunk.split("\n")) {
if (line.startsWith(">")) {
const [type2, message2] = splitFirst(line.slice(1), " ");
this._writeLine(type2, message2);
}
}
}
pushMessage(type2, data) {
if (this.replay) {
if (type2 === "update") {
if (this.replay === "spectator") {
const channelMessages = (0, import_battle.extractChannelMessages)(data, [0]);
this.push(channelMessages[0].join("\n"));
} else {
const channelMessages = (0, import_battle.extractChannelMessages)(data, [-1]);
this.push(channelMessages[-1].join("\n"));
}
}
return;
}
this.push(`${type2}
${data}`);
}
_writeLine(type, message) {
switch (type) {
case "start":
const options = JSON.parse(message);
options.send = (t, data) => {
if (Array.isArray(data))
data = data.join("\n");
this.pushMessage(t, data);
if (t === "end" && !this.keepAlive)
this.pushEnd();
};
if (this.debug)
options.debug = true;
try {
this.battle = new import_battle.Battle(options);
} catch (e) {
console.log(e);
}
break;
case "player":
const [slot, optionsText] = splitFirst(message, " ");
this.battle.setPlayer(slot, JSON.parse(optionsText));
break;
case "capture":
this.battle.inputLog.push(`>capture ${message}`);
const pokemon = this.battle.getPokemonByPNX(message);
if (!!pokemon) {
pokemon.capture();
} else {
throw new Error(`Capture targeted ${message} but that Pok\xE9mon does not exist.`);
}
break;
case "p1":
case "p2":
case "p3":
case "p4":
if (message === "undo") {
this.battle.undoChoice(type);
} else {
this.battle.choose(type, message);
}
break;
case "forcewin":
case "forcetie":
this.battle.win(type === "forcewin" ? message : null);
if (message) {
this.battle.inputLog.push(`>forcewin ${message}`);
} else {
this.battle.inputLog.push(`>forcetie`);
}
break;
case "forcelose":
this.battle.lose(message);
this.battle.inputLog.push(`>forcelose ${message}`);
break;
case "reseed":
const seed = message ? message.split(",").map(Number) : null;
this.battle.resetRNG(seed);
this.battle.inputLog.push(`>reseed ${this.battle.prng.seed.join(",")}`);
break;
case "tiebreak":
this.battle.tiebreak();
break;
case "chat-inputlogonly":
this.battle.inputLog.push(`>chat ${message}`);
break;
case "chat":
this.battle.inputLog.push(`>chat ${message}`);
this.battle.add("chat", `${message}`);
break;
case "eval":
const battle = this.battle;
battle.inputLog.push(`>${type} ${message}`);
message = message.replace(/\f/g, "\n");
battle.add("", ">>> " + message.replace(/\n/g, "\n||"));
try {
const p1 = battle.sides[0];
const p2 = battle.sides[1];
const p3 = battle.sides[2];
const p4 = battle.sides[3];
const p1active = p1?.active[0];
const p2active = p2?.active[0];
const p3active = p3?.active[0];
const p4active = p4?.active[0];
const toID = battle.toID;
const player = (input) => {
input = toID(input);
if (/^p[1-9]$/.test(input))
return battle.sides[parseInt(input.slice(1)) - 1];
if (/^[1-9]$/.test(input))
return battle.sides[parseInt(input) - 1];
for (const side2 of battle.sides) {
if (toID(side2.name) === input)
return side2;
}
return null;
};
const pokemon = (side2, input) => {
if (typeof side2 === "string")
side2 = player(side2);
input = toID(input);
if (/^[1-9]$/.test(input))
return side2.pokemon[parseInt(input) - 1];
return side2.pokemon.find((p) => p.baseSpecies.id === input || p.species.id === input);
};
let result = eval(message);
if (result?.then) {
result.then((unwrappedResult) => {
unwrappedResult = import_lib.Utils.visualize(unwrappedResult);
battle.add("", "Promise -> " + unwrappedResult);
battle.sendUpdates();
}, (error) => {
battle.add("", "<<< error: " + error.message);
battle.sendUpdates();
});
} else {
result = import_lib.Utils.visualize(result);
result = result.replace(/\n/g, "\n||");
battle.add("", "<<< " + result);
}
} catch (e) {
battle.add("", "<<< error: " + e.message);
}
break;
case "requestlog":
this.push(`requesteddata
${this.battle.inputLog.join("\n")}`);
break;
case "requestexport":
this.push(`requesteddata
${this.battle.prngSeed}
${this.battle.inputLog.join("\n")}`);
break;
case "requestteam":
message = message.trim();
const slotNum = parseInt(message.slice(1)) - 1;
if (isNaN(slotNum) || slotNum < 0) {
throw new Error(`Team requested for slot ${message}, but that slot does not exist.`);
}
const side = this.battle.sides[slotNum];
const team = import_teams.Teams.pack(side.team);
this.push(`requesteddata
${team}`);
break;
case "version":
case "version-origin":
break;
default:
throw new Error(`Unrecognized command ">${type} ${message}"`);
}
}
_writeEnd() {
if (!this.atEOF)
this.pushEnd();
this._destroy();
}
_destroy() {
if (this.battle)
this.battle.destroy();
}
}
function getPlayerStreams(stream) {
const streams = {
omniscient: new import_lib.Streams.ObjectReadWriteStream({
write(data) {
void stream.write(data);
},
writeEnd() {
return stream.writeEnd();
}
}),
spectator: new import_lib.Streams.ObjectReadStream({
read() {
}
}),
p1: new import_lib.Streams.ObjectReadWriteStream({
write(data) {
void stream.write(data.replace(/(^|\n)/g, `$1>p1 `));
}
}),
p2: new import_lib.Streams.ObjectReadWriteStream({
write(data) {
void stream.write(data.replace(/(^|\n)/g, `$1>p2 `));
}
}),
p3: new import_lib.Streams.ObjectReadWriteStream({
write(data) {
void stream.write(data.replace(/(^|\n)/g, `$1>p3 `));
}
}),
p4: new import_lib.Streams.ObjectReadWriteStream({
write(data) {
void stream.write(data.replace(/(^|\n)/g, `$1>p4 `));
}
})
};
(async () => {
for await (const chunk of stream) {
const [type2, data] = splitFirst(chunk, `
`);
switch (type2) {
case "update":
const channelMessages = (0, import_battle.extractChannelMessages)(data, [-1, 0, 1, 2, 3, 4]);
streams.omniscient.push(channelMessages[-1].join("\n"));
streams.spectator.push(channelMessages[0].join("\n"));
streams.p1.push(channelMessages[1].join("\n"));
streams.p2.push(channelMessages[2].join("\n"));
streams.p3.push(channelMessages[3].join("\n"));
streams.p4.push(channelMessages[4].join("\n"));
break;
case "sideupdate":
const [side2, sideData] = splitFirst(data, `
`);
streams[side2].push(sideData);
break;
case "end":
break;
}
}
for (const s of Object.values(streams)) {
s.pushEnd();
}
})().catch((err) => {
for (const s of Object.values(streams)) {
s.pushError(err, true);
}
});
return streams;
}
class BattlePlayer {
constructor(playerStream, debug = false) {
this.stream = playerStream;
this.log = [];
this.debug = debug;
}
async start() {
for await (const chunk of this.stream) {
this.receive(chunk);
}
}
receive(chunk) {
for (const line of chunk.split("\n")) {
this.receiveLine(line);
}
}
receiveLine(line) {
if (this.debug)
console.log(line);
if (!line.startsWith("|"))
return;
const [cmd, rest] = splitFirst(line.slice(1), "|");
if (cmd === "request")
return this.receiveRequest(JSON.parse(rest));
if (cmd === "error")
return this.receiveError(new Error(rest));
this.log.push(line);
}
receiveError(error) {
throw error;
}
choose(choice) {
void this.stream.write(choice);
}
}
class BattleTextStream extends import_lib.Streams.ReadWriteStream {
constructor(options2) {
super();
this.battleStream = new BattleStream(options2);
this.currentMessage = "";
void this._listen();
}
async _listen() {
for await (let message2 of this.battleStream) {
if (!message2.endsWith("\n"))
message2 += "\n";
this.push(message2 + "\n");
}
this.pushEnd();
}
_write(message2) {
this.currentMessage += "" + message2;
const index = this.currentMessage.lastIndexOf("\n");
if (index >= 0) {
void this.battleStream.write(this.currentMessage.slice(0, index));
this.currentMessage = this.currentMessage.slice(index + 1);
}
}
_writeEnd() {
return this.battleStream.writeEnd();
}
}
//# sourceMappingURL=battle-stream.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/battle-stream.ts"],
"sourcesContent": ["/**\r\n * Battle Stream\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Supports interacting with a PS battle in Stream format.\r\n *\r\n * This format is VERY NOT FINALIZED, please do not use it directly yet.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Streams, Utils} from '../lib';\r\nimport {Teams} from './teams';\r\nimport {Battle, extractChannelMessages} from './battle';\r\n\r\n/**\r\n * Like string.split(delimiter), but only recognizes the first `limit`\r\n * delimiters (default 1).\r\n *\r\n * `\"1 2 3 4\".split(\" \", 2) => [\"1\", \"2\"]`\r\n *\r\n * `Utils.splitFirst(\"1 2 3 4\", \" \", 1) => [\"1\", \"2 3 4\"]`\r\n *\r\n * Returns an array of length exactly limit + 1.\r\n */\r\nfunction splitFirst(str: string, delimiter: string, limit = 1) {\r\n\tconst splitStr: string[] = [];\r\n\twhile (splitStr.length < limit) {\r\n\t\tconst delimiterIndex = str.indexOf(delimiter);\r\n\t\tif (delimiterIndex >= 0) {\r\n\t\t\tsplitStr.push(str.slice(0, delimiterIndex));\r\n\t\t\tstr = str.slice(delimiterIndex + delimiter.length);\r\n\t\t} else {\r\n\t\t\tsplitStr.push(str);\r\n\t\t\tstr = '';\r\n\t\t}\r\n\t}\r\n\tsplitStr.push(str);\r\n\treturn splitStr;\r\n}\r\n\r\nexport class BattleStream extends Streams.ObjectReadWriteStream<string> {\r\n\tdebug: boolean;\r\n\tnoCatch: boolean;\r\n\treplay: boolean | 'spectator';\r\n\tkeepAlive: boolean;\r\n\tbattle: Battle | null;\r\n\r\n\tconstructor(options: {\r\n\t\tdebug?: boolean, noCatch?: boolean, keepAlive?: boolean, replay?: boolean | 'spectator',\r\n\t} = {}) {\r\n\t\tsuper();\r\n\t\tthis.debug = !!options.debug;\r\n\t\tthis.noCatch = !!options.noCatch;\r\n\t\tthis.replay = options.replay || false;\r\n\t\tthis.keepAlive = !!options.keepAlive;\r\n\t\tthis.battle = null;\r\n\t}\r\n\r\n\t_write(chunk: string) {\r\n\t\tif (this.noCatch) {\r\n\t\t\tthis._writeLines(chunk);\r\n\t\t} else {\r\n\t\t\ttry {\r\n\t\t\t\tthis._writeLines(chunk);\r\n\t\t\t} catch (err: any) {\r\n\t\t\t\tthis.pushError(err, true);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.battle) this.battle.sendUpdates();\r\n\t}\r\n\r\n\t_writeLines(chunk: string) {\r\n\t\tfor (const line of chunk.split('\\n')) {\r\n\t\t\tif (line.startsWith('>')) {\r\n\t\t\t\tconst [type, message] = splitFirst(line.slice(1), ' ');\r\n\t\t\t\tthis._writeLine(type, message);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpushMessage(type: string, data: string) {\r\n\t\tif (this.replay) {\r\n\t\t\tif (type === 'update') {\r\n\t\t\t\tif (this.replay === 'spectator') {\r\n\t\t\t\t\tconst channelMessages = extractChannelMessages(data, [0]);\r\n\t\t\t\t\tthis.push(channelMessages[0].join('\\n'));\r\n\t\t\t\t} else {\r\n\t\t\t\t\tconst channelMessages = extractChannelMessages(data, [-1]);\r\n\t\t\t\t\tthis.push(channelMessages[-1].join('\\n'));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tthis.push(`${type}\\n${data}`);\r\n\t}\r\n\r\n\t_writeLine(type: string, message: string) {\r\n\t\tswitch (type) {\r\n\t\tcase 'start':\r\n\t\t\tconst options = JSON.parse(message);\r\n\t\t\toptions.send = (t: string, data: any) => {\r\n\t\t\t\tif (Array.isArray(data)) data = data.join(\"\\n\");\r\n\t\t\t\tthis.pushMessage(t, data);\r\n\t\t\t\tif (t === 'end' && !this.keepAlive) this.pushEnd();\r\n\t\t\t};\r\n\t\t\tif (this.debug) options.debug = true;\r\n\t\t\ttry {\r\n\t\t\t\tthis.battle = new Battle(options);\r\n\t\t\t} catch (e) {\r\n\t\t\t\tconsole.log(e);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase 'player':\r\n\t\t\tconst [slot, optionsText] = splitFirst(message, ' ');\r\n\t\t\tthis.battle!.setPlayer(slot as SideID, JSON.parse(optionsText));\r\n\t\t\tbreak;\r\n\t\tcase 'capture':\r\n\t\t\tthis.battle!.inputLog.push(`>capture ${message}`);\r\n\t\t\tconst pokemon = this.battle!.getPokemonByPNX(message);\r\n\t\t\tif (!!pokemon) {\r\n\t\t\t\tpokemon.capture();\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error(`Capture targeted ${message} but that Pok\u00E9mon does not exist.`);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase 'p1':\r\n\t\tcase 'p2':\r\n\t\tcase 'p3':\r\n\t\tcase 'p4':\r\n\t\t\tif (message === 'undo') {\r\n\t\t\t\tthis.battle!.undoChoice(type);\r\n\t\t\t} else {\r\n\t\t\t\tthis.battle!.choose(type, message);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase 'forcewin':\r\n\t\tcase 'forcetie':\r\n\t\t\tthis.battle!.win(type === 'forcewin' ? message as SideID : null);\r\n\t\t\tif (message) {\r\n\t\t\t\tthis.battle!.inputLog.push(`>forcewin ${message}`);\r\n\t\t\t} else {\r\n\t\t\t\tthis.battle!.inputLog.push(`>forcetie`);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase 'forcelose':\r\n\t\t\tthis.battle!.lose(message as SideID);\r\n\t\t\tthis.battle!.inputLog.push(`>forcelose ${message}`);\r\n\t\t\tbreak;\r\n\t\tcase 'reseed':\r\n\t\t\tconst seed = message ? message.split(',').map(Number) as PRNGSeed : null;\r\n\t\t\tthis.battle!.resetRNG(seed);\r\n\t\t\t// could go inside resetRNG, but this makes using it in `eval` slightly less buggy\r\n\t\t\tthis.battle!.inputLog.push(`>reseed ${this.battle!.prng.seed.join(','Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,iBAA6B;AAC7B,mBAAoB;AACpB,oBAA6C;AAb7C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,SAAS,WAAW,KAAa,WAAmB,QAAQ,GAAG;AAC9D,QAAM,WAAqB,CAAC;AAC5B,SAAO,SAAS,SAAS,OAAO;AAC/B,UAAM,iBAAiB,IAAI,QAAQ,SAAS;AAC5C,QAAI,kBAAkB,GAAG;AACxB,eAAS,KAAK,IAAI,MAAM,GAAG,cAAc,CAAC;AAC1C,YAAM,IAAI,MAAM,iBAAiB,UAAU,MAAM;AAAA,IAClD,OAAO;AACN,eAAS,KAAK,GAAG;AACjB,YAAM;AAAA,IACP;AAAA,EACD;AACA,WAAS,KAAK,GAAG;AACjB,SAAO;AACR;AAEO,MAAM,qBAAqB,mBAAQ,sBAA8B;AAAA,EAOvE,YAAYA,WAER,CAAC,GAAG;AACP,UAAM;AACN,SAAK,QAAQ,CAAC,CAACA,SAAQ;AACvB,SAAK,UAAU,CAAC,CAACA,SAAQ;AACzB,SAAK,SAASA,SAAQ,UAAU;AAChC,SAAK,YAAY,CAAC,CAACA,SAAQ;AAC3B,SAAK,SAAS;AAAA,EACf;AAAA,EAEA,OAAO,OAAe;AACrB,QAAI,KAAK,SAAS;AACjB,WAAK,YAAY,KAAK;AAAA,IACvB,OAAO;AACN,UAAI;AACH,aAAK,YAAY,KAAK;AAAA,MACvB,SAAS,KAAP;AACD,aAAK,UAAU,KAAK,IAAI;AACxB;AAAA,MACD;AAAA,IACD;AACA,QAAI,KAAK;AAAQ,WAAK,OAAO,YAAY;AAAA,EAC1C;AAAA,EA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,MAAM;AACjB,mBAAO,KAAK,CAAC,oBAAyB;AACrC,gCAAkB,iBAAM,UAAU,eAAe;AACjD,qBAAO,IAAI,IAAI,gBAAgB,eAAe;AAC9C,qBAAO,YAAY;AAAA,YACpB,GAAG,CAAC,UAAiB;AACpB,qBAAO,IAAI,IAAI,gBAAgB,MAAM,OAAO;AAC5C,qBAAO,YAAY;AAAA,YACpB,CAAC;AAAA,UACF,OAAO;AACN,qBAAS,iBAAM,UAAU,MAAM;AAC/B,qBAAS,OAAO,QAAQ,OAAO,MAAM;AACrC,mBAAO,IAAI,IAAI,SAAS,MAAM;AAAA,UAC/B;AAAA,QACD,SAAS,GAAP;AACD,iBAAO,IAAI,IAAI,gBAAgB,EAAE,OAAO;AAAA,QACzC;AACA;AAAA,MACD,KAAK;AACJ,aAAK,KAAK;AAAA,EAAkB,KAAK,OAAQ,SAAS,KAAK,IAAI,GAAG;AAC9D;AAAA,MACD,KAAK;AACJ,aAAK,KAAK;AAAA,EAAkB,KAAK,OAAQ;AAAA,EAAa,KAAK,OAAQ,SAAS,KAAK,IAAI,GAAG;AACxF;AAAA,MACD,KAAK;AACJ,kBAAU,QAAQ,KAAK;AACvB,cAAM,UAAU,SAAS,QAAQ,MAAM,CAAC,CAAC,IAAI;AAC7C,YAAI,MAAM,OAAO,KAAK,UAAU,GAAG;AAClC,gBAAM,IAAI,MAAM,2BAA2B,wCAAwC;AAAA,QACpF;AACA,cAAM,OAAO,KAAK,OAAQ,MAAM,OAAO;AACvC,cAAM,OAAO,mBAAM,KAAK,KAAK,IAAI;AACjC,aAAK,KAAK;AAAA,EAAkB,MAAM;AAClC;AAAA,MACD,KAAK;AAAA,MACL,KAAK;AACJ;AAAA,MACD;AACC,cAAM,IAAI,MAAM,0BAA0B,QAAQ,UAAU;AAAA,IALine truncated
"names": ["options", "type", "message", "side"]
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/battle.ts"],
"sourcesContent": ["/**\r\n * Simulator Battle\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This file is where the battle simulation itself happens.\r\n *\r\n * The most important part of the simulation is the event system:\r\n * see the `runEvent` function definition for details.\r\n *\r\n * General battle mechanics are in `battle-actions`; move-specific,\r\n * item-specific, etc mechanics are in the corresponding file in\r\n * `data`.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Format} from './dex-formats';\r\nimport {Dex, toID} from './dex';\r\nimport {Teams} from './teams';\r\nimport {Field} from './field';\r\nimport {Pokemon, EffectState, RESTORATIVE_BERRIES} from './pokemon';\r\nimport {PRNG, PRNGSeed} from './prng';\r\nimport {Side} from './side';\r\nimport {State} from './state';\r\nimport {BattleQueue, Action} from './battle-queue';\r\nimport {BattleActions} from './battle-actions';\r\nimport {Utils} from '../lib';\r\ndeclare const __version: any;\r\n\r\nexport type ChannelID = 0 | 1 | 2 | 3 | 4;\r\n\r\nexport type ChannelMessages<T extends ChannelID | -1> = Record<T, string[]>;\r\n\r\nconst splitRegex = /^\\|split\\|p([1234])\\n(.*)\\n(.*)|.+/gm;\r\n\r\nexport function extractChannelMessages<T extends ChannelID | -1>(message: string, channelIds: T[]): ChannelMessages<T> {\r\n\tconst channelIdSet = new Set(channelIds);\r\n\tconst channelMessages: ChannelMessages<ChannelID | -1> = {\r\n\t\t[-1]: [],\r\n\t\t0: [],\r\n\t\t1: [],\r\n\t\t2: [],\r\n\t\t3: [],\r\n\t\t4: [],\r\n\t};\r\n\r\n\tfor (const [lineMatch, playerMatch, secretMessage, sharedMessage] of message.matchAll(splitRegex)) {\r\n\t\tconst player = playerMatch ? parseInt(playerMatch) : 0;\r\n\t\tfor (const channelId of channelIdSet) {\r\n\t\t\tlet line = lineMatch;\r\n\t\t\tif (player) {\r\n\t\t\t\tline = channelId === -1 || player === channelId ? secretMessage : sharedMessage;\r\n\t\t\t\tif (!line) continue;\r\n\t\t\t}\r\n\t\t\tchannelMessages[channelId].push(line);\r\n\t\t}\r\n\t}\r\n\r\n\treturn channelMessages;\r\n}\r\n\r\n\r\ninterface BattleOptions {\r\n\tformat?: Format;\r\n\tformatid: ID;\r\n\t/** Output callback */\r\n\tsend?: (type: string, data: string | string[]) => void;\r\n\tprng?: PRNG; // PRNG override (you usually don't need this, just pass a seed)\r\n\tseed?: PRNGSeed; // PRNG seed\r\n\trated?: boolean | string; // Rated string\r\n\tp1?: PlayerOptions; // Player 1 data\r\n\tp2?: PlayerOptions; // Player 2 data\r\n\tp3?: PlayerOptions; // Player 3 data\r\n\tp4?: PlayerOptions; // Player 4 data\r\n\tdebug?: boolean; // show debug mode option\r\n\tforceRandomChance?: boolean; // force Battle#randomChance to always return true or false (used in some tests)\r\n\tdeserialized?: boolean;\r\n\tstrictChoices?: boolean; // whether invalid choices should throw\r\n}\r\n\r\ninterface EventListenerWithoutPriority {\r\n\teffect: Effect;\r\n\ttarget?: Pokemon;\r\n\tindex?: number;\r\n\t// eslint-disable-next-line @typescript-eslint/ban-types\r\n\tcallback?: Function;\r\n\tstate: EffectState | null;\r\n\t// eslint-disable-next-line @typescript-eslint/ban-types\r\n\tend: Function | null;\r\n\tendCallArgs?: any[];\r\n\teffectHolder: Pokemon | Side | Field | Battle;\r\n}\r\ninterface EventListener extends EventListenerWithoutPriority {\r\n\torder: number | false;\r\n\tpriority: number;\r\n\tsubOrder: number;\r\n\tspeed?: number;\r\n}\r\n\r\ntype Part = string | number | boolean | Pokemon | Side | Effect | Move | null | undefined;\r\n\r\n// The current request state of the Battle:\r\n//\r\n// - 'teampreview': beginning of BW/XY/SM battle (Team Preview)\r\n// - 'move': beginning of each turn\r\n// - 'switch': end of turn if fainted (or mid turn with switching effects)\r\n// - '': no request. Used between turns, or when the battle is over.\r\n//\r\n// An individual Side's request state is encapsulated in its `activeRequest` field.\r\nexport type RequestState = 'teampreview' | 'move' | 'switch' | '';\r\n\r\nexport class Battle {\r\n\treadonly id: ID;\r\n\treadonly debugMode: boolean;\r\n\treadonly forceRandomChance: boolean | null;\r\n\treadonly deserialized: boolean;\r\n\treadonly strictChoices: boolean;\r\n\treadonly format: Format;\r\n\treadonly formatData: EffectState;\r\n\treadonly gameType: GameType;\r\n\t/**\r\n\t * The number of active pokemon per half-field.\r\n\t * See header comment in side.ts for details.\r\n\t */\r\n\treadonly activePerHalf: 1 | 2 | 3;\r\n\treadonly field: Field;\r\n\treadonly sides: [Side, Side] | [Side, Side, Side, Side];\r\n\treadonly prngSeed: PRNGSeed;\r\n\tdex: ModdedDex;\r\n\tgen: number;\r\n\truleTable: Dex.RuleTable;\r\n\tprng: PRNG;\r\n\trated: boolean | string;\r\n\treportExactHP: boolean;\r\n\treportPercentages: boolean;\r\n\tsupportCancel: boolean;\r\n\r\n\tactions: BattleActions;\r\n\tqueue: BattleQueue;\r\n\treadonly faintQueue: {\r\n\t\ttarget: Pokemon,\r\n\t\tsource: Pokemon | null,\r\n\t\teffect: Effect | null,\r\n\t}[];\r\n\r\n\treadonly log: string[];\r\n\treadonly Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,yBAAqB;AACrB,iBAAwB;AACxB,mBAAoB;AACpB,mBAAoB;AACpB,qBAAwD;AACxD,kBAA6B;AAC7B,kBAAmB;AACnB,mBAAoB;AACpB,0BAAkC;AAClC,4BAA4B;AAC5B,iBAAoB;AA1BpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCA,MAAM,aAAa;AAEZ,SAAS,uBAAiD,SAAiB,YAAqC;AACtH,QAAM,eAAe,IAAI,IAAI,UAAU;AACvC,QAAM,kBAAmD;AAAA,IACxD,CAAC,EAAE,GAAG,CAAC;AAAA,IACP,GAAG,CAAC;AAAA,IACJ,GAAG,CAAC;AAAA,IACJ,GAAG,CAAC;AAAA,IACJ,GAAG,CAAC;AAAA,IACJ,GAAG,CAAC;AAAA,EACL;AAEA,aAAW,CAAC,WAA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AACjC,QAAI,KAAK,YAAY;AACpB,UAAI,CAAC,QAAQ;AACZ,aAAK,WAAW,KAAK;AAAA,MACtB;AACA,WAAK,aAAa;AAClB,WAAK,gBAAgB;AACrB,WAAK,eAAe;AAAA,IACrB;AAAA,EACD;AAAA,EAEA,cAAc;AACb,eAAW,WAAW,KAAK,aAAa,GAAG;AAC1C,cAAQ,YAAY;AAAA,IACrB;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,gBAAgB,GAAc,GAAc;AAC3C,WLine truncated
"names": []
}
+56
View File
@@ -0,0 +1,56 @@
"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 cobbled_debug_client_exports = {};
__export(cobbled_debug_client_exports, {
startClient: () => startClient
});
module.exports = __toCommonJS(cobbled_debug_client_exports);
var Net = __toESM(require("net"));
var readline = __toESM(require("readline"));
function startClient(port) {
const client = new Net.Socket();
client.on("data", (data) => {
console.log(data.toString());
});
client.on("close", (data) => {
console.log("Connection closed.");
client.destroy();
});
client.connect(port, "localhost", () => {
console.log("Connected");
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on("line", (line) => {
client.write(line);
});
}
//# sourceMappingURL=cobbled-debug-client.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/cobbled-debug-client.ts"],
"sourcesContent": ["import * as Net from \"net\";\r\nimport * as readline from \"readline\";\r\n\r\nexport function startClient(port: number) {\r\n\tconst client = new Net.Socket();\r\n\r\n\tclient.on('data', (data) => {\r\n\t\tconsole.log(data.toString());\r\n\t});\r\n\r\n\tclient.on('close', (data) => {\r\n\t\tconsole.log('Connection closed.');\r\n\t\tclient.destroy();\r\n\t});\r\n\r\n\tclient.connect(port, 'localhost', () => {\r\n\t\tconsole.log('Connected');\r\n\t});\r\n\r\n\tconst rl = readline.createInterface({\r\n\t\tinput: process.stdin,\r\n\t\toutput: process.stdout,\r\n\t});\r\n\r\n\trl.on('line', (line) => {\r\n\t\tclient.write(line);\r\n\t});\r\n}\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAqB;AACrB,eAA0B;AAEnB,SAAS,YAAY,MAAc;AACzC,QAAM,SAAS,IAAI,IAAI,OAAO;AAE9B,SAAO,GAAG,QAAQ,CAAC,SAAS;AAC3B,YAAQ,IAAI,KAAK,SAAS,CAAC;AAAA,EAC5B,CAAC;AAED,SAAO,GAAG,SAAS,CAAC,SAAS;AAC5B,YAAQ,IAAI,oBAAoB;AAChC,WAAO,QAAQ;AAAA,EAChB,CAAC;AAED,SAAO,QAAQ,MAAM,aAAa,MAAM;AACvC,YAAQ,IAAI,WAAW;AAAA,EACxB,CAAC;AAED,QAAM,KAAK,SAAS,gBAAgB;AAAA,IACnC,OAAO,QAAQ;AAAA,IACf,QAAQ,QAAQ;AAAA,EACjB,CAAC;AAED,KAAG,GAAG,QAAQ,CAAC,SAAS;AACvB,WAAO,MAAM,IAAI;AAAA,EAClB,CAAC;AACF;",
"names": []
}
+120
View File
@@ -0,0 +1,120 @@
"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 cobbled_debug_server_exports = {};
__export(cobbled_debug_server_exports, {
startServer: () => startServer
});
module.exports = __toCommonJS(cobbled_debug_server_exports);
var import_battle_stream = require("./battle-stream");
var import_dex = require("./dex");
var Net = __toESM(require("net"));
var CobblemonCache = __toESM(require("./cobblemon-cache"));
function startServer(port) {
const server = Net.createServer();
const battleMap = /* @__PURE__ */ new Map();
server.listen(port, () => {
console.log("Server listening for connection requests on socket localhost: " + port);
});
server.on("connection", (socket) => onConnection(socket, battleMap));
}
function onData(socket, chunk, battleMap) {
const data = chunk.toString();
const lines = data.split("\n");
lines.forEach((line) => {
console.log("Data received from client: " + line.toString());
if (line.startsWith(">startbattle")) {
const battleId = line.split(" ")[1];
battleMap.set(battleId, new import_battle_stream.BattleStream());
} else if (line === ">getCobbledMoves") {
getCobbledMoves(socket);
} else if (line === ">getCobbledAbilityIds") {
getCobbledAbilityIds(socket);
} else if (line === ">getCobbledItemIds") {
getCobbledItemIds(socket);
} else if (line === ">resetSpeciesData") {
CobblemonCache.resetSpecies();
} else if (line.startsWith(">receiveSpeciesData")) {
const speciesJson = line.replace(`>receiveSpeciesData `, "");
const species = JSON.parse(speciesJson);
CobblemonCache.registerSpecies(species);
console.log("Received", species.id);
socket.write("ACK");
} else {
const [battleId, showdownMsg] = line.split("~");
const battleStream = battleMap.get(battleId);
if (battleStream) {
try {
void battleStream.write(showdownMsg);
} catch (err) {
console.error(err.stack);
}
writeBattleOutput(socket, battleStream);
}
}
});
}
function writeBattleOutput(socket, battleStream) {
const messages = battleStream.buf;
if (messages.length !== 0) {
socket.write(padNumber(messages.length, 8));
for (const message of messages) {
socket.write(padNumber(message.length, 8) + message);
}
} else {
writeVoid(socket);
}
battleStream.buf = [];
}
function writeVoid(socket) {
socket.write("00000000");
}
function onConnection(socket, battleMap) {
socket.on("data", (chunk) => onData(socket, chunk, battleMap));
socket.on("end", () => console.log("Closing connection with the client"));
socket.on("error", (err) => console.error(err.stack));
}
function getCobbledMoves(socket) {
const payload = JSON.stringify(import_dex.Dex.mod(CobblemonCache.MOD_ID).moves.all());
socket.write(padNumber(payload.length, 8) + payload);
}
function getCobbledAbilityIds(socket) {
const payload = JSON.stringify(import_dex.Dex.mod(CobblemonCache.MOD_ID).abilities.all().map((ability) => ability.id));
socket.write(padNumber(payload.length, 8) + payload);
}
function getCobbledItemIds(socket) {
const payload = JSON.stringify(import_dex.Dex.mod(CobblemonCache.MOD_ID).items.all().map((item) => item.id));
socket.write(padNumber(payload.length, 8) + payload);
}
function padNumber(num, size) {
let numStr = num.toString();
while (numStr.length < size)
numStr = "0" + numStr;
return numStr;
}
//# sourceMappingURL=cobbled-debug-server.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/cobbled-debug-server.ts"],
"sourcesContent": ["import {BattleStream} from \"./battle-stream\";\r\nimport {Dex} from \"./dex\";\r\nimport * as Net from \"net\";\r\nimport { Species } from \"./dex-species\";\r\nimport * as CobblemonCache from \"./cobblemon-cache\";\r\n\r\nexport function startServer(port: number): void {\r\n\tconst server = Net.createServer();\r\n\tconst battleMap = new Map<string, BattleStream>();\r\n\r\n\tserver.listen(port, () => {\r\n\t\tconsole.log('Server listening for connection requests on socket localhost: ' + port);\r\n\t});\r\n\r\n\tserver.on('connection', socket => onConnection(socket, battleMap));\r\n}\r\n\r\nfunction onData(socket: Net.Socket, chunk: Buffer, battleMap: Map<string, BattleStream>) {\r\n\tconst data = chunk.toString();\r\n\tconst lines = data.split('\\n');\r\n\tlines.forEach(line => {\r\n\t\tconsole.log('Data received from client: ' + line.toString());\r\n\t\tif (line.startsWith('>startbattle')) {\r\n\t\t\tconst battleId = line.split(' ')[1];\r\n\t\t\tbattleMap.set(battleId, new BattleStream());\r\n\t\t} else if (line === '>getCobbledMoves') {\r\n\t\t\tgetCobbledMoves(socket);\r\n\t\t} else if (line === '>getCobbledAbilityIds') {\r\n\t\t\tgetCobbledAbilityIds(socket);\r\n\t\t} else if (line === '>getCobbledItemIds') {\r\n\t\t\tgetCobbledItemIds(socket);\r\n\t\t} else if (line === '>resetSpeciesData') {\r\n\t\t\tCobblemonCache.resetSpecies();\r\n\t\t} else if (line.startsWith('>receiveSpeciesData')) {\r\n\t\t\tconst speciesJson = line.replace(`>receiveSpeciesData `, '');\r\n\t\t\tconst species = JSON.parse(speciesJson) as Species;\r\n\t\t\tCobblemonCache.registerSpecies(species);\r\n\t\t\tconsole.log('Received', species.id);\r\n\t\t\tsocket.write('ACK');\r\n\t\t} else {\r\n\t\t\tconst [battleId, showdownMsg] = line.split('~');\r\n\t\t\tconst battleStream = battleMap.get(battleId);\r\n\t\t\tif (battleStream) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tvoid battleStream.write(showdownMsg);\r\n\t\t\t\t} catch (err: any) {\r\n\t\t\t\t\tconsole.error(err.stack);\r\n\t\t\t\t}\r\n\r\n\t\t\t\twriteBattleOutput(socket, battleStream);\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}\r\n\r\nfunction writeBattleOutput(socket: Net.Socket, battleStream: BattleStream) {\r\n\tconst messages = battleStream.buf;\r\n\tif (messages.length !== 0) {\r\n\t\tsocket.write(padNumber(messages.length, 8));\r\n\t\tfor (const message of messages) {\r\n\t\t\tsocket.write(padNumber(message.length, 8) + message);\r\n\t\t}\r\n\t} else {\r\n\t\twriteVoid(socket);\r\n\t}\r\n\tbattleStream.buf = [];\r\n}\r\n\r\nfunction writeVoid(socket: Net.Socket) {\r\n\tsocket.write('00000000');\r\n}\r\n\r\nfunction onConnection(socket: Net.Socket, battleMap: Map<string, BattleStream>) {\r\n\tsocket.on('data', (chunk) => onData(socket, chunk, battleMap));\r\n\tsocket.on('end', () => console.log('Closing connection with the client'));\r\n\tsocket.on('error', (err) => console.error(err.stack));\r\n}\r\n\r\nfunction getCobbledMoves(socket: Net.Socket) {\r\n\tconst payload = JSON.stringify(Dex.mod(CobblemonCache.MOD_ID).moves.all());\r\n\tsocket.write(padNumber(payload.length, 8) + payload);\r\n}\r\n\r\nfunction getCobbledAbilityIds(socket: Net.Socket) {\r\n\tconst payload = JSON.stringify(Dex.mod(CobblemonCache.MOD_ID).abilities.all().map(ability => ability.id));\r\n\tsocket.write(padNumber(payload.length, 8) + payload);\r\n}\r\n\r\nfunction getCobbledItemIds(socket: Net.Socket) {\r\n\tconst payload = JSON.stringify(Dex.mod(CobblemonCache.MOD_ID).items.all().map(item => item.id));\r\n\tsocket.write(padNumber(payload.length, 8) + payload);\r\n}\r\n\r\nfunction padNumber(num: number, size: number): string {\r\n\tlet numStr = num.toString();\r\n\twhile (numStr.length < size) numStr = \"0\" + numStr;\r\n\treturn numStr;\r\n}\r\n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Ae,MAAM,EAAE,MAAM,IAAI,EAAE,IAAI,UAAQ,KAAK,EAAE,CAAC;AAC9F,SAAO,MAAM,UAAU,QAAQ,QAAQ,CAAC,IAAI,OAAO;AACpD;AAEA,SAAS,UAAU,KAAa,MAAsB;AACrD,MAAI,SAAS,IAAI,SAAS;AAC1B,SAAO,OAAO,SAAS;AAAM,aAAS,MAAM;AAC5C,SAAO;AACR;",
"names": []
}
+45
View File
@@ -0,0 +1,45 @@
"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 cobblemon_cache_exports = {};
__export(cobblemon_cache_exports, {
MOD_ID: () => MOD_ID,
allCache: () => allCache,
registerSpecies: () => registerSpecies,
resetSpecies: () => resetSpecies,
speciesByID: () => speciesByID
});
module.exports = __toCommonJS(cobblemon_cache_exports);
var import_dex_species = require("./dex-species");
const MOD_ID = "cobblemon";
const cobblemonSpecies = /* @__PURE__ */ new Map();
function registerSpecies(speciesData) {
const species = new import_dex_species.Species(speciesData);
cobblemonSpecies.set(species.id, species);
return species;
}
function resetSpecies() {
cobblemonSpecies.clear();
}
function speciesByID(id) {
return cobblemonSpecies.get(id);
}
function allCache() {
return Array.from(cobblemonSpecies.values());
}
//# sourceMappingURL=cobblemon-cache.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/cobblemon-cache.ts"],
"sourcesContent": ["import { Species } from \"./dex-species\";\r\n\r\nexport const MOD_ID = 'cobblemon';\r\n\r\nconst cobblemonSpecies = new Map<ID, Species>();\r\n\r\nexport function registerSpecies(speciesData: AnyObject): Species {\r\n\tconst species = new Species(speciesData);\r\n\tcobblemonSpecies.set(species.id, species);\r\n\treturn species;\r\n}\r\n\r\nexport function resetSpecies() {\r\n\tcobblemonSpecies.clear();\r\n}\r\n\r\nexport function speciesByID(id: ID): Species | undefined {\r\n\treturn cobblemonSpecies.get(id);\r\n}\r\n\r\nexport function allCache(): Species[] {\r\n\treturn Array.from(cobblemonSpecies.values());\r\n}\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAwB;AAEjB,MAAM,SAAS;AAEtB,MAAM,mBAAmB,oBAAI,IAAiB;AAEvC,SAAS,gBAAgB,aAAiC;AAChE,QAAM,UAAU,IAAI,2BAAQ,WAAW;AACvC,mBAAiB,IAAI,QAAQ,IAAI,OAAO;AACxC,SAAO;AACR;AAEO,SAAS,eAAe;AAC9B,mBAAiB,MAAM;AACxB;AAEO,SAAS,YAAY,IAA6B;AACxD,SAAO,iBAAiB,IAAI,EAAE;AAC/B;AAEO,SAAS,WAAsB;AACrC,SAAO,MAAM,KAAK,iBAAiB,OAAO,CAAC;AAC5C;",
"names": []
}
+109
View File
@@ -0,0 +1,109 @@
"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 dex_abilities_exports = {};
__export(dex_abilities_exports, {
Ability: () => Ability,
DexAbilities: () => DexAbilities
});
module.exports = __toCommonJS(dex_abilities_exports);
var import_dex_data = require("./dex-data");
class Ability extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
this.fullname = `ability: ${this.name}`;
this.effectType = "Ability";
this.suppressWeather = !!data.suppressWeather;
this.rating = data.rating || 0;
if (!this.gen) {
if (this.num >= 268) {
this.gen = 9;
} else if (this.num >= 234) {
this.gen = 8;
} else if (this.num >= 192) {
this.gen = 7;
} else if (this.num >= 165) {
this.gen = 6;
} else if (this.num >= 124) {
this.gen = 5;
} else if (this.num >= 77) {
this.gen = 4;
} else if (this.num >= 1) {
this.gen = 3;
}
}
}
}
class DexAbilities {
constructor(dex) {
this.abilityCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.dex = dex;
}
get(name = "") {
if (name && typeof name !== "string")
return name;
const id = (0, import_dex_data.toID)(name);
return this.getByID(id);
}
getByID(id) {
let ability = this.abilityCache.get(id);
if (ability)
return ability;
if (this.dex.data.Aliases.hasOwnProperty(id)) {
ability = this.get(this.dex.data.Aliases[id]);
} else if (id && this.dex.data.Abilities.hasOwnProperty(id)) {
const abilityData = this.dex.data.Abilities[id];
const abilityTextData = this.dex.getDescs("Abilities", id, abilityData);
ability = new Ability({
name: id,
...abilityData,
...abilityTextData
});
if (ability.gen > this.dex.gen) {
ability.isNonstandard = "Future";
}
if (this.dex.currentMod === "gen7letsgo" && ability.id !== "noability") {
ability.isNonstandard = "Past";
}
if ((this.dex.currentMod === "gen7letsgo" || this.dex.gen <= 2) && ability.id === "noability") {
ability.isNonstandard = null;
}
} else {
ability = new Ability({
id,
name: id,
exists: false
});
}
if (ability.exists)
this.abilityCache.set(id, ability);
return ability;
}
all() {
if (this.allCache)
return this.allCache;
const abilities = [];
for (const id in this.dex.data.Abilities) {
abilities.push(this.getByID(id));
}
this.allCache = abilities;
return this.allCache;
}
}
//# sourceMappingURL=dex-abilities.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-abilities.ts"],
"sourcesContent": ["import {PokemonEventMethods} from './dex-conditions';\r\nimport {BasicEffect, toID} from './dex-data';\r\n\r\ninterface AbilityEventMethods {\r\n\tonCheckShow?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonEnd?: (this: Battle, target: Pokemon & Side & Field) => void;\r\n\tonPreStart?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonStart?: (this: Battle, target: Pokemon) => void;\r\n}\r\n\r\nexport interface AbilityData extends Partial<Ability>, AbilityEventMethods, PokemonEventMethods {\r\n\tname: string;\r\n}\r\n\r\nexport type ModdedAbilityData = AbilityData | Partial<AbilityData> & {inherit: true};\r\n\r\nexport class Ability extends BasicEffect implements Readonly<BasicEffect> {\r\n\tdeclare readonly effectType: 'Ability';\r\n\r\n\t/** Rating from -1 Detrimental to +5 Essential; see `data/abilities.ts` for details. */\r\n\treadonly rating: number;\r\n\treadonly suppressWeather: boolean;\r\n\tdeclare readonly condition?: ConditionData;\r\n\tdeclare readonly isPermanent?: boolean;\r\n\tdeclare readonly isBreakable?: boolean;\r\n\r\n\tconstructor(data: AnyObject) {\r\n\t\tsuper(data);\r\n\r\n\t\tthis.fullname = `ability: ${this.name}`;\r\n\t\tthis.effectType = 'Ability';\r\n\t\tthis.suppressWeather = !!data.suppressWeather;\r\n\t\tthis.rating = data.rating || 0;\r\n\r\n\t\tif (!this.gen) {\r\n\t\t\tif (this.num >= 268) {\r\n\t\t\t\tthis.gen = 9;\r\n\t\t\t} else if (this.num >= 234) {\r\n\t\t\t\tthis.gen = 8;\r\n\t\t\t} else if (this.num >= 192) {\r\n\t\t\t\tthis.gen = 7;\r\n\t\t\t} else if (this.num >= 165) {\r\n\t\t\t\tthis.gen = 6;\r\n\t\t\t} else if (this.num >= 124) {\r\n\t\t\t\tthis.gen = 5;\r\n\t\t\t} else if (this.num >= 77) {\r\n\t\t\t\tthis.gen = 4;\r\n\t\t\t} else if (this.num >= 1) {\r\n\t\t\t\tthis.gen = 3;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nexport class DexAbilities {\r\n\treadonly dex: ModdedDex;\r\n\treadonly abilityCache = new Map<ID, Ability>();\r\n\tallCache: readonly Ability[] | null = null;\r\n\r\n\tconstructor(dex: ModdedDex) {\r\n\t\tthis.dex = dex;\r\n\t}\r\n\r\n\tget(name: string | Ability = ''): Ability {\r\n\t\tif (name && typeof name !== 'string') return name;\r\n\r\n\t\tconst id = toID(name);\r\n\t\treturn this.getByID(id);\r\n\t}\r\n\r\n\tgetByID(id: ID): Ability {\r\n\t\tlet ability = this.abilityCache.get(id);\r\n\t\tif (ability) return ability;\r\n\r\n\t\tif (this.dex.data.Aliases.hasOwnProperty(id)) {\r\n\t\t\tability = this.get(this.dex.data.Aliases[id]);\r\n\t\t} else if (id && this.dex.data.Abilities.hasOwnProperty(id)) {\r\n\t\t\tconst abilityData = this.dex.data.Abilities[id] as any;\r\n\t\t\tconst abilityTextData = this.dex.getDescs('Abilities', id, abilityData);\r\n\t\t\tability = new Ability({\r\n\t\t\t\tname: id,\r\n\t\t\t\t...abilityData,\r\n\t\t\t\t...abilityTextData,\r\n\t\t\t});\r\n\t\t\tif (ability.gen > this.dex.gen) {\r\n\t\t\t\t(ability as any).isNonstandard = 'Future';\r\n\t\t\t}\r\n\t\t\tif (this.dex.currentMod === 'gen7letsgo' && ability.id !== 'noability') {\r\n\t\t\t\t(ability as any).isNonstandard = 'Past';\r\n\t\t\t}\r\n\t\t\tif ((this.dex.currentMod === 'gen7letsgo' || this.dex.gen <= 2) && ability.id === 'noability') {\r\n\t\t\t\t(ability as any).isNonstandard = null;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tability = new Ability({\r\n\t\t\t\tid, name: id, exists: false,\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tif (ability.exists) this.abilityCache.set(id, ability);\r\n\t\treturn ability;\r\n\t}\r\n\r\n\tall(): readonly Ability[] {\r\n\t\tif (this.allCache) return this.allCache;\r\n\t\tconst abilities = [];\r\n\t\tfor (const id in this.dex.data.Abilities) {\r\n\t\t\tabilities.push(this.getByID(id as ID));\r\n\t\t}\r\n\t\tthis.allCache = abilities;\r\n\t\treturn this.allCache;\r\n\t}\r\n}\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAgC;AAezB,MAAM,gBAAgB,4BAA6C;AAAA,EAUzE,YAAY,MAAiB;AAC5B,UAAM,IAAI;AAEV,SAAK,WAAW,YAAY,KAAK;AACjC,SAAK,aAAa;AAClB,SAAK,kBAAkB,CAAC,CAAC,KAAK;AAC9B,SAAK,SAAS,KAAK,UAAU;AAE7B,QAAI,CAAC,KAAK,KAAK;AACd,UAAI,KAAK,OAAO,KAAK;AACpB,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,KAAK;AAC3B,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,KAAK;AAC3B,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,KAAK;AAC3B,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,KAAK;AAC3B,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,IAAI;AAC1B,aAAK,MAAM;AAAA,MACZ,WAAW,KAAK,OAAO,GAAG;AACzB,aAAK,MAAM;AAAA,MACZ;AAAA,IACD;AAAA,EACD;AACD;AAEO,MAAM,aAAa;AAAA,EAKzB,YAAY,KAAgB;AAH5B,SAAS,eAAe,oBAAI,IAAiB;AAC7C,oBAAsC;AAGrC,SAAK,MAAM;AAAA,EACZ;AAAA,EAEA,IAAI,OAAyB,IAAa;AACzC,QAAI,QAAQ,OAAO,SAAS;AAAU,aAAO;AAE7C,UAAM,SAAK,sBAAK,IAAI;AACpB,WAAO,KAAK,QAAQ,EAAE;AAAA,EACvB;AAA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 -0,0 +1,76 @@
"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 dex_conditions_exports = {};
__export(dex_conditions_exports, {
Condition: () => Condition,
DexConditions: () => DexConditions
});
module.exports = __toCommonJS(dex_conditions_exports);
var import_dex_data = require("./dex-data");
class Condition extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
data = this;
this.effectType = ["Weather", "Status"].includes(data.effectType) ? data.effectType : "Condition";
}
}
const EMPTY_CONDITION = new Condition({ name: "", exists: false });
class DexConditions {
constructor(dex) {
this.conditionCache = /* @__PURE__ */ new Map();
this.dex = dex;
}
get(name) {
if (!name)
return EMPTY_CONDITION;
if (typeof name !== "string")
return name;
return this.getByID(name.startsWith("item:") || name.startsWith("ability:") ? name : (0, import_dex_data.toID)(name));
}
getByID(id) {
if (!id)
return EMPTY_CONDITION;
let condition = this.conditionCache.get(id);
if (condition)
return condition;
let found;
if (id.startsWith("item:")) {
const item = this.dex.items.getByID(id.slice(5));
condition = { ...item, id: "item:" + item.id };
} else if (id.startsWith("ability:")) {
const ability = this.dex.abilities.getByID(id.slice(8));
condition = { ...ability, id: "ability:" + ability.id };
} else if (this.dex.data.Rulesets.hasOwnProperty(id)) {
condition = this.dex.formats.get(id);
} else if (this.dex.data.Conditions.hasOwnProperty(id)) {
condition = new Condition({ name: id, ...this.dex.data.Conditions[id] });
} else if (this.dex.data.Moves.hasOwnProperty(id) && (found = this.dex.data.Moves[id]).condition || this.dex.data.Abilities.hasOwnProperty(id) && (found = this.dex.data.Abilities[id]).condition || this.dex.data.Items.hasOwnProperty(id) && (found = this.dex.data.Items[id]).condition) {
condition = new Condition({ name: found.name || id, ...found.condition });
} else if (id === "recoil") {
condition = new Condition({ name: "Recoil", effectType: "Recoil" });
} else if (id === "drain") {
condition = new Condition({ name: "Drain", effectType: "Drain" });
} else {
condition = new Condition({ name: id, exists: false });
}
this.conditionCache.set(id, condition);
return condition;
}
}
//# sourceMappingURL=dex-conditions.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-conditions.ts"],
"sourcesContent": ["import {BasicEffect, toID} from './dex-data';\r\nimport type {SecondaryEffect, MoveEventMethods} from './dex-moves';\r\n\r\nexport interface EventMethods {\r\n\tonDamagingHit?: (this: Battle, damage: number, target: Pokemon, source: Pokemon, move: ActiveMove) => void;\r\n\tonEmergencyExit?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonAfterEachBoost?: (this: Battle, boost: SparseBoostsTable, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonAfterHit?: MoveEventMethods['onAfterHit'];\r\n\tonAfterMega?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonAfterSetStatus?: (this: Battle, status: Condition, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonAfterSubDamage?: MoveEventMethods['onAfterSubDamage'];\r\n\tonAfterSwitchInSelf?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonAfterTerastallization?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonAfterUseItem?: (this: Battle, item: Item, pokemon: Pokemon) => void;\r\n\tonAfterTakeItem?: (this: Battle, item: Item, pokemon: Pokemon) => void;\r\n\tonAfterBoost?: (this: Battle, boost: SparseBoostsTable, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonAfterFaint?: (this: Battle, length: number, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonAfterMoveSecondarySelf?: MoveEventMethods['onAfterMoveSecondarySelf'];\r\n\tonAfterMoveSecondary?: MoveEventMethods['onAfterMoveSecondary'];\r\n\tonAfterMove?: MoveEventMethods['onAfterMove'];\r\n\tonAfterMoveSelf?: CommonHandlers['VoidSourceMove'];\r\n\tonAttract?: (this: Battle, target: Pokemon, source: Pokemon) => void;\r\n\tonAccuracy?: (\r\n\t\tthis: Battle, accuracy: number, target: Pokemon, source: Pokemon, move: ActiveMove\r\n\t) => number | boolean | null | void;\r\n\tonBasePower?: CommonHandlers['ModifierSourceMove'];\r\n\tonBeforeFaint?: (this: Battle, pokemon: Pokemon, effect: Effect) => void;\r\n\tonBeforeMove?: CommonHandlers['VoidSourceMove'];\r\n\tonBeforeSwitchIn?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonBeforeSwitchOut?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonBeforeTurn?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonChangeBoost?: (this: Battle, boost: SparseBoostsTable, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonTryBoost?: (this: Battle, boost: SparseBoostsTable, target: Pokemon, source: Pokemon, effect: Effect) => void;\r\n\tonChargeMove?: CommonHandlers['VoidSourceMove'];\r\n\tonCriticalHit?: ((this: Battle, pokemon: Pokemon, source: null, move: ActiveMove) => boolean | void) | boolean;\r\n\tonDamage?: (\r\n\t\tthis: Battle, damage: number, target: Pokemon, source: Pokemon, effect: Effect\r\n\t) => number | boolean | null | void;\r\n\tonDeductPP?: (this: Battle, target: Pokemon, source: Pokemon) => number | void;\r\n\tonDisableMove?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonDragOut?: (this: Battle, pokemon: Pokemon, source?: Pokemon, move?: ActiveMove) => void;\r\n\tonEatItem?: (this: Battle, item: Item, pokemon: Pokemon) => void;\r\n\tonEffectiveness?: MoveEventMethods['onEffectiveness'];\r\n\tonEntryHazard?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonFaint?: CommonHandlers['VoidEffect'];\r\n\tonFlinch?: ((this: Battle, pokemon: Pokemon) => boolean | void) | boolean;\r\n\tonFractionalPriority?: CommonHandlers['ModifierSourceMove'] | -0.1;\r\n\tonHit?: MoveEventMethods['onHit'];\r\n\tonImmunity?: (this: Battle, type: string, pokemon: Pokemon) => void;\r\n\tonLockMove?: string | ((this: Battle, pokemon: Pokemon) => void | string);\r\n\tonMaybeTrapPokemon?: (this: Battle, pokemon: Pokemon) => void;\r\n\tonModifyAccuracy?: CommonHandlers['ModifierMove'];\r\n\tonModifyAtk?: CommonHandlers['ModifierSourceMove'];\r\n\tonModifyBoost?: (this: Battle, boosts: SparseBoostsTable, pokemon: Pokemon) => SparseBoostsTable | void;\r\n\tonModifyCritRatio?: CommonHandlers['ModifierSourceMove'];\r\n\tonModifyDamage?: CommonHandlers['ModifierSourceMove'];\r\n\tonModifyDef?: CommonHandlers['ModifierMove'];\r\n\tonModifyMove?: MoveEventMethods['onModifyMove'];\r\n\tonModifyPriority?: CommonHandlers['ModifierSourceMove'];\r\n\tonModifySecondaries?: (\r\n\t\tthis: Battle, secondaries: SecondaryEffect[], target: Pokemon, source: Pokemon, move: ActiveMove\r\n\t) => void;\r\n\tonModifyType?: MoveEventMethods['onModifyType'];\r\n\tonModifyTarget?: MoveEventMethods['onModifyTarget'];\r\n\tonModifySpA?: CommonHandlers['ModifierSourceMove'];\r\n\tonModifySpD?: CommonHandlers['ModifierMove'];\r\n\tonModifySpe?: (this: Battle, spe: number, pokemon: Pokemon) => number | void;\r\n\tonModifyWeight?: (this: Battle, weighthg: number, pokemon: Pokemon) => number | void;\r\n\tonMoveAborted?: CommonHandlers['VoidMove'];\r\n\tonNegateImmunity?: ((this: Battle, pokemon: Pokemon, type: string) => boolean | void) | boolean;\r\n\tonOverrideAction?: (this: Battle, pokemon: Pokemon, target: Pokemon, move: ActiveMove) => string | void;\r\n\tonPrepareHit?: CommonHandlers['ResultSourceMove'];\r\n\tonRLine truncated
"mappings": ";;;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AK,IAAI,KAAK,WAAW,eAAe,EAAE,GAAG;AACvD,kBAAY,IAAI,UAAU,EAAC,MAAM,IAAI,GAAG,KAAK,IAAI,KAAK,WAAW,EAAE,EAAC,CAAC;AAAA,IACtE,WACE,KAAK,IAAI,KAAK,MAAM,eAAe,EAAE,MAAM,QAAQ,KAAK,IAAI,KAAK,MAAM,EAAE,GAAG,aAC5E,KAAK,IAAI,KAAK,UAAU,eAAe,EAAE,MAAM,QAAQ,KAAK,IAAI,KAAK,UAAU,EAAE,GAAG,aACpF,KAAK,IAAI,KAAK,MAAM,eAAe,EAAE,MAAM,QAAQ,KAAK,IAAI,KAAK,MAAM,EAAE,GAAG,WAC5E;AACD,kBAAY,IAAI,UAAU,EAAC,MAAM,MAAM,QAAQ,IAAI,GAAG,MAAM,UAAS,CAAC;AAAA,IACvE,WAAW,OAAO,UAAU;AAC3B,kBAAY,IAAI,UAAU,EAAC,MAAM,UAAU,YAAY,SAAQ,CAAC;AAAA,IACjE,WAAW,OAAO,SAAS;AAC1B,kBAAY,IAAI,UAAU,EAAC,MAAM,SAAS,YAAY,QAAO,CAAC;AAAA,IAC/D,OAAO;AACN,kBAAY,IAAI,UAAU,EAAC,MAAM,IAAI,QAAQ,MAAK,CAAC;AAAA,IACpD;AAEA,SAAK,eAAe,IAAI,IAAI,SAAS;AACrC,WAAO;AAAA,EACR;AACD;",
"names": []
}
+288
View File
@@ -0,0 +1,288 @@
"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 dex_data_exports = {};
__export(dex_data_exports, {
BasicEffect: () => BasicEffect,
DexNatures: () => DexNatures,
DexStats: () => DexStats,
DexTypes: () => DexTypes,
Nature: () => Nature,
TypeInfo: () => TypeInfo,
toID: () => toID
});
module.exports = __toCommonJS(dex_data_exports);
var import_lib = require("../lib");
/**
* Dex Data
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
function toID(text) {
if (text && text.id) {
text = text.id;
} else if (text && text.userid) {
text = text.userid;
} else if (text && text.roomid) {
text = text.roomid;
}
if (typeof text !== "string" && typeof text !== "number")
return "";
return ("" + text).toLowerCase().replace(/[^a-z0-9]+/g, "");
}
class BasicEffect {
constructor(data) {
this.exists = true;
Object.assign(this, data);
this.name = import_lib.Utils.getString(data.name).trim();
this.id = data.realMove ? toID(data.realMove) : toID(this.name);
this.fullname = import_lib.Utils.getString(data.fullname) || this.name;
this.effectType = import_lib.Utils.getString(data.effectType) || "Condition";
this.exists = !!(this.exists && this.id);
this.num = data.num || 0;
this.gen = data.gen || 0;
this.shortDesc = data.shortDesc || "";
this.desc = data.desc || "";
this.isNonstandard = data.isNonstandard || null;
this.duration = data.duration;
this.noCopy = !!data.noCopy;
this.affectsFainted = !!data.affectsFainted;
this.status = data.status || void 0;
this.weather = data.weather || void 0;
this.sourceEffect = data.sourceEffect || "";
}
toString() {
return this.name;
}
}
class Nature extends BasicEffect {
constructor(data) {
super(data);
data = this;
this.fullname = `nature: ${this.name}`;
this.effectType = "Nature";
this.gen = 3;
this.plus = data.plus || void 0;
this.minus = data.minus || void 0;
}
}
class DexNatures {
constructor(dex) {
this.natureCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.dex = dex;
}
get(name) {
if (name && typeof name !== "string")
return name;
return this.getByID(toID(name));
}
getByID(id) {
let nature = this.natureCache.get(id);
if (nature)
return nature;
if (this.dex.data.Aliases.hasOwnProperty(id)) {
nature = this.get(this.dex.data.Aliases[id]);
if (nature.exists) {
this.natureCache.set(id, nature);
}
return nature;
}
if (id && this.dex.data.Natures.hasOwnProperty(id)) {
const natureData = this.dex.data.Natures[id];
nature = new Nature(natureData);
if (nature.gen > this.dex.gen)
nature.isNonstandard = "Future";
} else {
nature = new Nature({ name: id, exists: false });
}
if (nature.exists)
this.natureCache.set(id, nature);
return nature;
}
all() {
if (this.allCache)
return this.allCache;
const natures = [];
for (const id in this.dex.data.Natures) {
natures.push(this.getByID(id));
}
this.allCache = natures;
return this.allCache;
}
}
class TypeInfo {
constructor(data) {
this.exists = true;
Object.assign(this, data);
this.name = data.name;
this.id = data.id;
this.effectType = import_lib.Utils.getString(data.effectType) || "Type";
this.exists = !!(this.exists && this.id);
this.gen = data.gen || 0;
this.isNonstandard = data.isNonstandard || null;
this.damageTaken = data.damageTaken || {};
this.HPivs = data.HPivs || {};
this.HPdvs = data.HPdvs || {};
}
toString() {
return this.name;
}
}
class DexTypes {
constructor(dex) {
this.typeCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.namesCache = null;
this.dex = dex;
}
get(name) {
if (name && typeof name !== "string")
return name;
return this.getByID(toID(name));
}
getByID(id) {
let type = this.typeCache.get(id);
if (type)
return type;
const typeName = id.charAt(0).toUpperCase() + id.substr(1);
if (typeName && this.dex.data.TypeChart.hasOwnProperty(id)) {
type = new TypeInfo({ name: typeName, id, ...this.dex.data.TypeChart[id] });
} else {
type = new TypeInfo({ name: typeName, id, exists: false, effectType: "EffectType" });
}
if (type.exists)
this.typeCache.set(id, type);
return type;
}
names() {
if (this.namesCache)
return this.namesCache;
this.namesCache = this.all().filter((type) => !type.isNonstandard).map((type) => type.name);
return this.namesCache;
}
isName(name) {
const id = name.toLowerCase();
const typeName = id.charAt(0).toUpperCase() + id.substr(1);
return name === typeName && this.dex.data.TypeChart.hasOwnProperty(id);
}
all() {
if (this.allCache)
return this.allCache;
const types = [];
for (const id in this.dex.data.TypeChart) {
types.push(this.getByID(id));
}
this.allCache = types;
return this.allCache;
}
}
const idsCache = ["hp", "atk", "def", "spa", "spd", "spe"];
const reverseCache = {
__proto: null,
"hitpoints": "hp",
"attack": "atk",
"defense": "def",
"specialattack": "spa",
"spatk": "spa",
"spattack": "spa",
"specialatk": "spa",
"special": "spa",
"spc": "spa",
"specialdefense": "spd",
"spdef": "spd",
"spdefense": "spd",
"specialdef": "spd",
"speed": "spe"
};
class DexStats {
constructor(dex) {
if (dex.gen !== 1) {
this.shortNames = {
__proto__: null,
hp: "HP",
atk: "Atk",
def: "Def",
spa: "SpA",
spd: "SpD",
spe: "Spe"
};
this.mediumNames = {
__proto__: null,
hp: "HP",
atk: "Attack",
def: "Defense",
spa: "Sp. Atk",
spd: "Sp. Def",
spe: "Speed"
};
this.names = {
__proto__: null,
hp: "HP",
atk: "Attack",
def: "Defense",
spa: "Special Attack",
spd: "Special Defense",
spe: "Speed"
};
} else {
this.shortNames = {
__proto__: null,
hp: "HP",
atk: "Atk",
def: "Def",
spa: "Spc",
spd: "[SpD]",
spe: "Spe"
};
this.mediumNames = {
__proto__: null,
hp: "HP",
atk: "Attack",
def: "Defense",
spa: "Special",
spd: "[Sp. Def]",
spe: "Speed"
};
this.names = {
__proto__: null,
hp: "HP",
atk: "Attack",
def: "Defense",
spa: "Special",
spd: "[Special Defense]",
spe: "Speed"
};
}
}
getID(name) {
if (name === "Spd")
return "spe";
const id = toID(name);
if (reverseCache[id])
return reverseCache[id];
if (idsCache.includes(id))
return id;
return null;
}
ids() {
return idsCache;
}
}
//# sourceMappingURL=dex-data.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-data.ts"],
"sourcesContent": ["/**\r\n * Dex Data\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\nimport {Utils} from '../lib';\r\n\r\n/**\r\n* Converts anything to an ID. An ID must have only lowercase alphanumeric\r\n* characters.\r\n*\r\n* If a string is passed, it will be converted to lowercase and\r\n* non-alphanumeric characters will be stripped.\r\n*\r\n* If an object with an ID is passed, its ID will be returned.\r\n* Otherwise, an empty string will be returned.\r\n*\r\n* Generally assigned to the global toID, because of how\r\n* commonly it's used.\r\n*/\r\nexport function toID(text: any): ID {\r\n\t// The sucrase transformation of optional chaining is too expensive to be used in a hot function like this.\r\n\t/* eslint-disable @typescript-eslint/prefer-optional-chain */\r\n\tif (text && text.id) {\r\n\t\ttext = text.id;\r\n\t} else if (text && text.userid) {\r\n\t\ttext = text.userid;\r\n\t} else if (text && text.roomid) {\r\n\t\ttext = text.roomid;\r\n\t}\r\n\tif (typeof text !== 'string' && typeof text !== 'number') return '';\r\n\treturn ('' + text).toLowerCase().replace(/[^a-z0-9]+/g, '') as ID;\r\n\t/* eslint-enable @typescript-eslint/prefer-optional-chain */\r\n}\r\n\r\nexport class BasicEffect implements EffectData {\r\n\t/**\r\n\t * ID. This will be a lowercase version of the name with all the\r\n\t * non-alphanumeric characters removed. So, for instance, \"Mr. Mime\"\r\n\t * becomes \"mrmime\", and \"Basculin-Blue-Striped\" becomes\r\n\t * \"basculinbluestriped\".\r\n\t */\r\n\tid: ID;\r\n\t/**\r\n\t * Name. Currently does not support Unicode letters, so \"Flab\u00E9b\u00E9\"\r\n\t * is \"Flabebe\" and \"Nidoran\u2640\" is \"Nidoran-F\".\r\n\t */\r\n\tname: string;\r\n\t/**\r\n\t * Full name. Prefixes the name with the effect type. For instance,\r\n\t * Leftovers would be \"item: Leftovers\", confusion the status\r\n\t * condition would be \"confusion\", etc.\r\n\t */\r\n\tfullname: string;\r\n\t/** Effect type. */\r\n\teffectType: EffectType;\r\n\t/**\r\n\t * Does it exist? For historical reasons, when you use an accessor\r\n\t * for an effect that doesn't exist, you get a dummy effect that\r\n\t * doesn't do anything, and this field set to false.\r\n\t */\r\n\texists: boolean;\r\n\t/**\r\n\t * Dex number? For a Pokemon, this is the National Dex number. For\r\n\t * other effects, this is often an internal ID (e.g. a move\r\n\t * number). Not all effects have numbers, this will be 0 if it\r\n\t * doesn't. Nonstandard effects (e.g. CAP effects) will have\r\n\t * negative numbers.\r\n\t */\r\n\tnum: number;\r\n\t/**\r\n\t * The generation of Pokemon game this was INTRODUCED (NOT\r\n\t * necessarily the current gen being simulated.) Not all effects\r\n\t * track generation; this will be 0 if not known.\r\n\t */\r\n\tgen: number;\r\n\t/**\r\n\t * A shortened form of the description of this effect.\r\n\t * Not all effects have this.\r\n\t */\r\n\tshortDesc: string;\r\n\t/** The full description for this effect. */\r\n\tdesc: string;\r\n\t/**\r\n\t * Is this item/move/ability/pokemon nonstandard? Specified for effects\r\n\t * that have no use in standard formats: made-up pokemon (CAP),\r\n\t * glitches (MissingNo etc), Pokestar pokemon, etc.\r\n\t */\r\n\tisNonstandard: Nonstandard | null;\r\n\t/** The duration of the condition - only for pure conditions. */\r\n\tduration?: number;\r\n\t/** Whether or not the condition is ignored by Baton Pass - only for pure conditions. */\r\n\tnoCopy: boolean;\r\n\t/** Whether or not the condition affects fainted Pokemon. */\r\n\taffectsFainted: boolean;\r\n\t/** Moves only: what status does it set? */\r\n\tstatus?: ID;\r\n\t/** Moves only: what weather does it set? */\r\n\tweather?: ID;\r\n\t/** ??? */\r\n\tsourceEffect: string;\r\n\r\n\tconstructor(data: AnyObject) {\r\n\t\tthis.exists = true;\r\n\t\tObject.assign(this, data);\r\n\r\n\t\tthis.name = Utils.getString(data.name).trim();\r\n\t\tthis.id = data.realMove ? toID(data.realMove) : toID(this.name); // Hidden Power hack\r\n\t\tthis.fullname = Utils.getString(data.fullname) || this.name;\r\n\t\tthis.effectType = Utils.getString(data.effectType) as EffectType || 'Condition';\r\n\t\tthis.exists = !!(this.exists && this.id);\r\n\t\tthis.num = data.num || 0;\r\n\t\tthis.gen = data.gen || 0;\r\n\t\tthis.shortDesc = data.shortDesc || '';\r\n\t\tthis.desc = data.desc || '';\r\n\t\tthis.isNonstandard = data.isNonstandard || null;\r\n\t\tthis.duration = data.duration;\r\n\t\tthis.noCopy = !!data.noCopy;\r\n\t\tthis.affectsFainted = !!data.affectsFainted;\r\n\t\tthis.status = data.status as ID || undefined;\r\n\t\tthis.weather = data.weather as ID || undefined;\r\n\t\tthis.sourceEffect = data.sourceEffect || '';\r\n\t}\r\n\r\n\ttoString() {\r\n\t\treturn this.name;\r\n\t}\r\n}\r\n\r\nexport class Nature extends BasicEffect implements Readonly<BasicEffect & NatureData> {\r\n\treadonly effectType: 'Nature';\r\n\treadonly plus?: StatIDExceptHP;\r\n\treadonly minus?: StatIDExceptHP;\r\Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,iBAAoB;AANpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,SAAS,KAAK,MAAe;AAGnC,MAAI,QAAQ,KAAK,IAAI;AACpB,WAAO,KAAK;AAAA,EACb,WAAW,QAAQ,KAAK,QAAQ;AAC/B,WAAO,KAAK;AAAA,EACb,WAAW,QAAQ,KAAK,QAAQ;AAC/B,WAAO,KAAK;AAAA,EACb;AACA,MAAI,OAAO,SAAS,YAAY,OAAO,SAAS;AAAU,WAAO;AACjE,UAAQ,KAAK,MAAM,YAAY,EAAE,QAAQ,eAAe,EAAE;AAE3D;AAEO,MAAM,YAAkC;AAAA,EAmE9C,YAAY,MAAiB;AAC5B,SAAK,SAAS;AACd,WAAO,OAAO,MAAM,IAAI;AAExB,SAAK,OAAO,iBAAM,UAAU,KAAK,IAAI,EAAE,KAAK;AAC5C,SAAK,KAAK,KAAK,WAAW,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;AAC9D,SAAK,WAAW,iBAAM,UAAU,KAAK,QAAQ,KAAK,KAAK;AACvD,SAAK,aAAa,iBAAM,UAAU,KAAK,UAAU,KAAmB;AACpE,SAAK,SAAS,CAAC,EAAE,KAAK,UAAU,KAAK;AACrC,SAAK,MAAM,KAAK,OAAO;AACvB,SAAK,MAAM,KAAK,OAAO;AACvB,SA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QAAU,KAAK;AAAA,QAAW,KAAK;AAAA,QAAW,KAAK;AAAA,QAAqB,KAAK;AAAA,MAC1G;AAAA,IACLine truncated
"names": []
}
+799
View File
@@ -0,0 +1,799 @@
"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 dex_formats_exports = {};
__export(dex_formats_exports, {
DexFormats: () => DexFormats,
Format: () => Format,
RuleTable: () => RuleTable
});
module.exports = __toCommonJS(dex_formats_exports);
var import_lib = require("../lib");
var import_dex_data = require("./dex-data");
var import_tags = require("../data/tags");
const DEFAULT_MOD = "gen9";
class RuleTable extends Map {
constructor() {
super();
this.complexBans = [];
this.complexTeamBans = [];
this.checkCanLearn = null;
this.timer = null;
this.tagRules = [];
this.valueRules = /* @__PURE__ */ new Map();
}
isBanned(thing) {
if (this.has(`+${thing}`))
return false;
return this.has(`-${thing}`);
}
isBannedSpecies(species) {
if (this.has(`+pokemon:${species.id}`))
return false;
if (this.has(`-pokemon:${species.id}`))
return true;
if (this.has(`+basepokemon:${(0, import_dex_data.toID)(species.baseSpecies)}`))
return false;
if (this.has(`-basepokemon:${(0, import_dex_data.toID)(species.baseSpecies)}`))
return true;
for (const tagid in import_tags.Tags) {
const tag = import_tags.Tags[tagid];
if (this.has(`-pokemontag:${tagid}`)) {
if ((tag.speciesFilter || tag.genericFilter)(species))
return true;
}
}
for (const tagid in import_tags.Tags) {
const tag = import_tags.Tags[tagid];
if (this.has(`+pokemontag:${tagid}`)) {
if ((tag.speciesFilter || tag.genericFilter)(species))
return false;
}
}
return this.has(`-pokemontag:allpokemon`);
}
isRestricted(thing) {
if (this.has(`+${thing}`))
return false;
return this.has(`*${thing}`);
}
isRestrictedSpecies(species) {
if (this.has(`+pokemon:${species.id}`))
return false;
if (this.has(`*pokemon:${species.id}`))
return true;
if (this.has(`+basepokemon:${(0, import_dex_data.toID)(species.baseSpecies)}`))
return false;
if (this.has(`*basepokemon:${(0, import_dex_data.toID)(species.baseSpecies)}`))
return true;
for (const tagid in import_tags.Tags) {
const tag = import_tags.Tags[tagid];
if (this.has(`*pokemontag:${tagid}`)) {
if ((tag.speciesFilter || tag.genericFilter)(species))
return true;
}
}
for (const tagid in import_tags.Tags) {
const tag = import_tags.Tags[tagid];
if (this.has(`+pokemontag:${tagid}`)) {
if ((tag.speciesFilter || tag.genericFilter)(species))
return false;
}
}
return this.has(`*pokemontag:allpokemon`);
}
getTagRules() {
const tagRules = [];
for (const ruleid of this.keys()) {
if (/^[+*-]pokemontag:/.test(ruleid)) {
const banid = ruleid.slice(12);
if (banid === "allpokemon" || banid === "allitems" || banid === "allmoves" || banid === "allabilities" || banid === "allnatures") {
} else {
tagRules.push(ruleid);
}
} else if ("+*-".includes(ruleid.charAt(0)) && ruleid.slice(1) === "nonexistent") {
tagRules.push(ruleid.charAt(0) + "pokemontag:nonexistent");
}
}
this.tagRules = tagRules.reverse();
return this.tagRules;
}
/**
* - non-empty string: banned, string is the reason
* - '': whitelisted
* - null: neither whitelisted nor banned
*/
check(thing, setHas = null) {
if (this.has(`+${thing}`))
return "";
if (setHas)
setHas[thing] = true;
return this.getReason(`-${thing}`);
}
getReason(key) {
const source = this.get(key);
if (source === void 0)
return null;
if (key === "-nonexistent" || key.startsWith("obtainable")) {
return "not obtainable";
}
return source ? `banned by ${source}` : `banned`;
}
blame(key) {
const source = this.get(key);
return source ? ` from ${source}` : ``;
}
getComplexBanIndex(complexBans, rule) {
const ruleId = (0, import_dex_data.toID)(rule);
let complexBanIndex = -1;
for (let i = 0; i < complexBans.length; i++) {
if ((0, import_dex_data.toID)(complexBans[i][0]) === ruleId) {
complexBanIndex = i;
break;
}
}
return complexBanIndex;
}
addComplexBan(rule, source, limit, bans) {
const complexBanIndex = this.getComplexBanIndex(this.complexBans, rule);
if (complexBanIndex !== -1) {
if (this.complexBans[complexBanIndex][2] === Infinity)
return;
this.complexBans[complexBanIndex] = [rule, source, limit, bans];
} else {
this.complexBans.push([rule, source, limit, bans]);
}
}
addComplexTeamBan(rule, source, limit, bans) {
const complexBanTeamIndex = this.getComplexBanIndex(this.complexTeamBans, rule);
if (complexBanTeamIndex !== -1) {
if (this.complexTeamBans[complexBanTeamIndex][2] === Infinity)
return;
this.complexTeamBans[complexBanTeamIndex] = [rule, source, limit, bans];
} else {
this.complexTeamBans.push([rule, source, limit, bans]);
}
}
/** After a RuleTable has been filled out, resolve its hardcoded numeric properties */
resolveNumbers(format, dex) {
const gameTypeMinTeamSize = ["triples", "rotation"].includes(format.gameType) ? 3 : format.gameType === "doubles" ? 2 : 1;
this.minTeamSize = Number(this.valueRules.get("minteamsize")) || 0;
this.maxTeamSize = Number(this.valueRules.get("maxteamsize")) || 6;
this.pickedTeamSize = Number(this.valueRules.get("pickedteamsize")) || null;
this.maxTotalLevel = Number(this.valueRules.get("maxtotallevel")) || null;
this.maxMoveCount = Number(this.valueRules.get("maxmovecount")) || 4;
this.minSourceGen = Number(this.valueRules.get("minsourcegen")) || 1;
this.minLevel = Number(this.valueRules.get("minlevel")) || 1;
this.maxLevel = Number(this.valueRules.get("maxlevel")) || 100;
this.defaultLevel = Number(this.valueRules.get("defaultlevel")) || 0;
this.adjustLevel = Number(this.valueRules.get("adjustlevel")) || null;
this.adjustLevelDown = Number(this.valueRules.get("adjustleveldown")) || null;
this.evLimit = Number(this.valueRules.get("evlimit")) || null;
if (this.valueRules.get("pickedteamsize") === "Auto") {
this.pickedTeamSize = ["doubles", "rotation"].includes(format.gameType) ? 4 : format.gameType === "triples" ? 6 : 3;
}
if (this.valueRules.get("evlimit") === "Auto") {
this.evLimit = dex.gen > 2 ? 510 : null;
if (format.mod === "gen7letsgo") {
this.evLimit = this.has("allowavs") ? null : 0;
}
}
if (this.maxTeamSize > 24) {
throw new Error(`Max team size ${this.maxTeamSize}${this.blame("maxteamsize")} is unsupported (we only support up to 24).`);
}
if (this.maxLevel > 99999) {
throw new Error(`Max level ${this.maxLevel}${this.blame("maxlevel")} is unsupported (we only support up to 99999)`);
}
if (this.maxMoveCount > 24) {
throw new Error(`Max move count ${this.maxMoveCount}${this.blame("maxmovecount")} is unsupported (we only support up to 24)`);
}
if (!this.defaultLevel) {
const maxTeamSize = this.pickedTeamSize || this.maxTeamSize;
if (this.maxTotalLevel && this.maxLevel > 100 && this.maxLevel * maxTeamSize > this.maxTotalLevel) {
this.defaultLevel = 100;
} else {
this.defaultLevel = this.maxLevel;
}
}
if (this.minTeamSize && this.minTeamSize < gameTypeMinTeamSize) {
throw new Error(`Min team size ${this.minTeamSize}${this.blame("minteamsize")} must be at least ${gameTypeMinTeamSize} for a ${format.gameType} game.`);
}
if (this.pickedTeamSize && this.pickedTeamSize < gameTypeMinTeamSize) {
throw new Error(`Chosen team size ${this.pickedTeamSize}${this.blame("pickedteamsize")} must be at least ${gameTypeMinTeamSize} for a ${format.gameType} game.`);
}
if (this.minTeamSize && this.pickedTeamSize && this.minTeamSize < this.pickedTeamSize) {
throw new Error(`Min team size ${this.minTeamSize}${this.blame("minteamsize")} is lower than chosen team size ${this.pickedTeamSize}${this.blame("pickedteamsize")}.`);
}
if (!this.minTeamSize)
this.minTeamSize = Math.max(gameTypeMinTeamSize, this.pickedTeamSize || 0);
if (this.maxTeamSize < gameTypeMinTeamSize) {
throw new Error(`Max team size ${this.maxTeamSize}${this.blame("maxteamsize")} must be at least ${gameTypeMinTeamSize} for a ${format.gameType} game.`);
}
if (this.maxTeamSize < this.minTeamSize) {
throw new Error(`Max team size ${this.maxTeamSize}${this.blame("maxteamsize")} must be at least min team size ${this.minTeamSize}${this.blame("minteamsize")}.`);
}
if (this.minLevel > this.maxLevel) {
throw new Error(`Min level ${this.minLevel}${this.blame("minlevel")} should not be above max level ${this.maxLevel}${this.blame("maxlevel")}.`);
}
if (this.defaultLevel > this.maxLevel) {
throw new Error(`Default level ${this.defaultLevel}${this.blame("defaultlevel")} should not be above max level ${this.maxLevel}${this.blame("maxlevel")}.`);
}
if (this.defaultLevel < this.minLevel) {
throw new Error(`Default level ${this.defaultLevel}${this.blame("defaultlevel")} should not be below min level ${this.minLevel}${this.blame("minlevel")}.`);
}
if (this.adjustLevelDown && this.adjustLevelDown >= this.maxLevel) {
throw new Error(`Adjust Level Down ${this.adjustLevelDown}${this.blame("adjustleveldown")} will have no effect because it's not below max level ${this.maxLevel}${this.blame("maxlevel")}.`);
}
if (this.adjustLevel && this.valueRules.has("minlevel")) {
throw new Error(`Min Level ${this.minLevel}${this.blame("minlevel")} will have no effect because you're using Adjust Level ${this.adjustLevel}${this.blame("adjustlevel")}.`);
}
if (this.evLimit && this.evLimit >= 1512) {
throw new Error(`EV Limit ${this.evLimit}${this.blame("evlimit")} will have no effect because it's not lower than 1512, the maximum possible combination of 252 EVs in every stat (if you currently have an EV limit, use "! EV Limit" to remove the limit).`);
}
if (this.evLimit && this.evLimit < 0) {
throw new Error(`EV Limit ${this.evLimit}${this.blame("evlimit")} can't be less than 0 (you might have meant: "! EV Limit" to remove the limit, or "EV Limit = 0" to ban EVs).`);
}
if (format.cupLevelLimit) {
throw new Error(`cupLevelLimit.range[0], cupLevelLimit.range[1], cupLevelLimit.total are now rules, respectively: "Min Level = NUMBER", "Max Level = NUMBER", and "Max Total Level = NUMBER"`);
}
if (format.teamLength) {
throw new Error(`teamLength.validate[0], teamLength.validate[1], teamLength.battle are now rules, respectively: "Min Team Size = NUMBER", "Max Team Size = NUMBER", and "Picked Team Size = NUMBER"`);
}
if (format.minSourceGen) {
throw new Error(`minSourceGen is now a rule: "Min Source Gen = NUMBER"`);
}
if (format.maxLevel) {
throw new Error(`maxLevel is now a rule: "Max Level = NUMBER"`);
}
if (format.defaultLevel) {
throw new Error(`defaultLevel is now a rule: "Default Level = NUMBER"`);
}
if (format.forcedLevel) {
throw new Error(`forcedLevel is now a rule: "Adjust Level = NUMBER"`);
}
if (format.maxForcedLevel) {
throw new Error(`maxForcedLevel is now a rule: "Adjust Level Down = NUMBER"`);
}
}
hasComplexBans() {
return this.complexBans?.length > 0 || this.complexTeamBans?.length > 0;
}
}
class Format extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
data = this;
this.mod = import_lib.Utils.getString(data.mod) || "gen9";
this.effectType = import_lib.Utils.getString(data.effectType) || "Format";
this.debug = !!data.debug;
this.rated = typeof data.rated === "string" ? data.rated : data.rated !== false;
this.gameType = data.gameType || "singles";
this.ruleset = data.ruleset || [];
this.baseRuleset = data.baseRuleset || [];
this.banlist = data.banlist || [];
this.restricted = data.restricted || [];
this.unbanlist = data.unbanlist || [];
this.customRules = data.customRules || null;
this.ruleTable = null;
this.onBegin = data.onBegin || void 0;
this.noLog = !!data.noLog;
}
}
function mergeFormatLists(main, custom) {
const result = [];
const build = [];
let current = { section: "", formats: [] };
for (const element of main) {
if (element.section) {
current = { section: element.section, column: element.column, formats: [] };
build.push(current);
} else if (element.name) {
current.formats.push(element);
}
}
if (custom !== void 0) {
for (const element of custom) {
if (element.section) {
current = build.find((e) => e.section === element.section);
if (current === void 0) {
current = { section: element.section, column: element.column, formats: [] };
build.push(current);
}
} else if (element.name) {
current.formats.push(element);
}
}
}
for (const element of build) {
result.push({ section: element.section, column: element.column }, ...element.formats);
}
return result;
}
class DexFormats {
constructor(dex) {
this.rulesetCache = /* @__PURE__ */ new Map();
this.dex = dex;
this.formatsListCache = null;
}
load() {
if (!this.dex.isBase)
throw new Error(`This should only be run on the base mod`);
this.dex.includeMods();
if (this.formatsListCache)
return this;
const formatsList = [];
let customFormats;
try {
customFormats = require(`${__dirname}/../config/custom-formats`).Formats;
if (!Array.isArray(customFormats)) {
throw new TypeError(`Exported property 'Formats' from "./config/custom-formats.ts" must be an array`);
}
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ENOENT") {
throw e;
}
}
let Formats = require(`${__dirname}/../config/formats`).Formats;
if (!Array.isArray(Formats)) {
throw new TypeError(`Exported property 'Formats' from "./config/formats.ts" must be an array`);
}
if (customFormats)
Formats = mergeFormatLists(Formats, customFormats);
let section = "";
let column = 1;
for (const [i, format] of Formats.entries()) {
const id = (0, import_dex_data.toID)(format.name);
if (format.section)
section = format.section;
if (format.column)
column = format.column;
if (!format.name && format.section)
continue;
if (!id) {
throw new RangeError(`Format #${i + 1} must have a name with alphanumeric characters, not '${format.name}'`);
}
if (!format.section)
format.section = section;
if (!format.column)
format.column = column;
if (this.rulesetCache.has(id))
throw new Error(`Format #${i + 1} has a duplicate ID: '${id}'`);
format.effectType = "Format";
format.baseRuleset = format.ruleset ? format.ruleset.slice() : [];
if (format.challengeShow === void 0)
format.challengeShow = true;
if (format.searchShow === void 0)
format.searchShow = true;
if (format.tournamentShow === void 0)
format.tournamentShow = true;
if (format.mod === void 0)
format.mod = "gen9";
if (!this.dex.dexes[format.mod])
throw new Error(`Format "${format.name}" requires nonexistent mod: '${format.mod}'`);
const ruleset = new Format(format);
this.rulesetCache.set(id, ruleset);
formatsList.push(ruleset);
}
this.formatsListCache = formatsList;
return this;
}
/**
* Returns a sanitized format ID if valid, or throws if invalid.
*/
validate(name) {
const [formatName, customRulesString] = name.split("@@@", 2);
const format = this.get(formatName);
if (!format.exists)
throw new Error(`Unrecognized format "${formatName}"`);
if (!customRulesString)
return format.id;
const ruleTable = this.getRuleTable(format);
const customRules = customRulesString.split(",").map((rule) => {
rule = rule.replace(/[\r\n|]*/g, "").trim();
const ruleSpec = this.validateRule(rule);
if (typeof ruleSpec === "string" && ruleTable.has(ruleSpec))
return null;
return rule;
}).filter(Boolean);
if (!customRules.length)
throw new Error(`The format already has your custom rules`);
const validatedFormatid = format.id + "@@@" + customRules.join(",");
const moddedFormat = this.get(validatedFormatid, true);
this.getRuleTable(moddedFormat);
return validatedFormatid;
}
get(name, isTrusted = false) {
if (name && typeof name !== "string")
return name;
name = (name || "").trim();
let id = (0, import_dex_data.toID)(name);
if (!name.includes("@@@")) {
const ruleset = this.rulesetCache.get(id);
if (ruleset)
return ruleset;
}
if (this.dex.data.Aliases.hasOwnProperty(id)) {
name = this.dex.data.Aliases[id];
id = (0, import_dex_data.toID)(name);
}
if (this.dex.data.Rulesets.hasOwnProperty(DEFAULT_MOD + id)) {
id = DEFAULT_MOD + id;
}
let supplementaryAttributes = null;
if (name.includes("@@@")) {
if (!isTrusted) {
try {
name = this.validate(name);
isTrusted = true;
} catch {
}
}
const [newName, customRulesString] = name.split("@@@", 2);
name = newName.trim();
id = (0, import_dex_data.toID)(name);
if (isTrusted && customRulesString) {
supplementaryAttributes = {
customRules: customRulesString.split(","),
searchShow: false
};
}
}
let effect;
if (this.dex.data.Rulesets.hasOwnProperty(id)) {
effect = new Format({ name, ...this.dex.data.Rulesets[id], ...supplementaryAttributes });
} else {
effect = new Format({ id, name, exists: false });
}
return effect;
}
all() {
this.load();
return this.formatsListCache;
}
getRuleTable(format, depth = 1, repeals) {
if (format.ruleTable && !repeals)
return format.ruleTable;
if (depth === 1) {
const dex = this.dex.mod(format.mod);
if (dex !== this.dex) {
return dex.formats.getRuleTable(format, 2, repeals);
}
}
const ruleTable = new RuleTable();
const ruleset = format.ruleset.slice();
for (const ban of format.banlist) {
ruleset.push("-" + ban);
}
for (const ban of format.restricted) {
ruleset.push("*" + ban);
}
for (const ban of format.unbanlist) {
ruleset.push("+" + ban);
}
if (format.customRules) {
ruleset.push(...format.customRules);
}
if (format.checkCanLearn) {
ruleTable.checkCanLearn = [format.checkCanLearn, format.name];
}
if (format.timer) {
ruleTable.timer = [format.timer, format.name];
}
for (const rule of ruleset) {
if (rule.startsWith("!") && !rule.startsWith("!!")) {
const ruleSpec = this.validateRule(rule, format);
if (!repeals)
repeals = /* @__PURE__ */ new Map();
repeals.set(ruleSpec.slice(1), depth);
}
}
for (const rule of ruleset) {
const ruleSpec = this.validateRule(rule, format);
if (typeof ruleSpec !== "string") {
if (ruleSpec[0] === "complexTeamBan") {
const complexTeamBan = ruleSpec.slice(1);
ruleTable.addComplexTeamBan(complexTeamBan[0], complexTeamBan[1], complexTeamBan[2], complexTeamBan[3]);
} else if (ruleSpec[0] === "complexBan") {
const complexBan = ruleSpec.slice(1);
ruleTable.addComplexBan(complexBan[0], complexBan[1], complexBan[2], complexBan[3]);
} else {
throw new Error(`Unrecognized rule spec ${ruleSpec}`);
}
continue;
}
if (rule.startsWith("!") && !rule.startsWith("!!")) {
const repealDepth = repeals.get(ruleSpec.slice(1));
if (repealDepth === void 0)
throw new Error(`Multiple "${rule}" rules in ${format.name}`);
if (repealDepth === depth) {
throw new Error(`Rule "${rule}" did nothing because "${rule.slice(1)}" is not in effect`);
}
if (repealDepth === -depth)
repeals.delete(ruleSpec.slice(1));
continue;
}
if ("+*-".includes(ruleSpec.charAt(0))) {
if (ruleTable.has(ruleSpec)) {
throw new Error(`Rule "${rule}" in "${format.name}" already exists in "${ruleTable.get(ruleSpec) || format.name}"`);
}
for (const prefix of "+*-")
ruleTable.delete(prefix + ruleSpec.slice(1));
ruleTable.set(ruleSpec, "");
continue;
}
let [formatid, value] = ruleSpec.split("=");
const subformat = this.get(formatid);
const repealAndReplace = ruleSpec.startsWith("!!");
if (repeals?.has(subformat.id)) {
repeals.set(subformat.id, -Math.abs(repeals.get(subformat.id)));
continue;
}
if (subformat.hasValue) {
if (value === void 0)
throw new Error(`Rule "${ruleSpec}" should have a value (like "${ruleSpec} = something")`);
if (value === "Current Gen")
value = `${this.dex.gen}`;
if ((subformat.id === "pickedteamsize" || subformat.id === "evlimit") && value === "Auto") {
} else if (subformat.hasValue === "integer" || subformat.hasValue === "positive-integer") {
const intValue = parseInt(value);
if (isNaN(intValue) || value !== `${intValue}`) {
throw new Error(`In rule "${ruleSpec}", "${value}" must be an integer number.`);
}
}
if (subformat.hasValue === "positive-integer") {
if (parseInt(value) === 0) {
throw new Error(`In rule "${ruleSpec}", "${value}" must be positive (to remove it, use the rule "! ${subformat.name}").`);
}
if (parseInt(value) <= 0) {
throw new Error(`In rule "${ruleSpec}", "${value}" must be positive.`);
}
}
const oldValue = ruleTable.valueRules.get(subformat.id);
if (oldValue === value) {
throw new Error(`Rule "${ruleSpec}" is redundant with existing rule "${subformat.id}=${value}"${ruleTable.blame(subformat.id)}.`);
} else if (repealAndReplace) {
if (oldValue === void 0) {
if (subformat.mutuallyExclusiveWith && ruleTable.valueRules.has(subformat.mutuallyExclusiveWith)) {
if (this.dex.formats.get(subformat.mutuallyExclusiveWith).ruleset.length) {
throw new Error(`This format does not support "!!"`);
}
ruleTable.valueRules.delete(subformat.mutuallyExclusiveWith);
ruleTable.delete(subformat.mutuallyExclusiveWith);
} else {
throw new Error(`Rule "${ruleSpec}" is not replacing anything (it should not have "!!")`);
}
}
} else {
if (oldValue !== void 0) {
throw new Error(`Rule "${ruleSpec}" conflicts with "${subformat.id}=${oldValue}"${ruleTable.blame(subformat.id)} (Use "!! ${ruleSpec}" to override "${subformat.id}=${oldValue}".)`);
}
if (subformat.mutuallyExclusiveWith && ruleTable.valueRules.has(subformat.mutuallyExclusiveWith)) {
const oldRule = `"${subformat.mutuallyExclusiveWith}=${ruleTable.valueRules.get(subformat.mutuallyExclusiveWith)}"`;
throw new Error(`Format can't simultaneously have "${ruleSpec}" and ${oldRule}${ruleTable.blame(subformat.mutuallyExclusiveWith)} (Use "!! ${ruleSpec}" to override ${oldRule}.)`);
}
}
ruleTable.valueRules.set(subformat.id, value);
} else {
if (value !== void 0)
throw new Error(`Rule "${ruleSpec}" should not have a value (no equals sign)`);
if (repealAndReplace)
throw new Error(`"!!" is not supported for this rule`);
if (ruleTable.has(subformat.id) && !repealAndReplace) {
throw new Error(`Rule "${rule}" in "${format.name}" already exists in "${ruleTable.get(subformat.id) || format.name}"`);
}
}
ruleTable.set(subformat.id, "");
if (depth > 16) {
throw new Error(`Excessive ruleTable recursion in ${format.name}: ${ruleSpec} of ${format.ruleset}`);
}
const subRuleTable = this.getRuleTable(subformat, depth + 1, repeals);
for (const [ruleid, sourceFormat] of subRuleTable) {
if (!repeals?.has(ruleid)) {
const newValue = subRuleTable.valueRules.get(ruleid);
const oldValue = ruleTable.valueRules.get(ruleid);
if (newValue !== void 0) {
const subSubFormat = this.get(ruleid);
if (subSubFormat.mutuallyExclusiveWith && ruleTable.valueRules.has(subSubFormat.mutuallyExclusiveWith)) {
throw new Error(`Rule "${ruleid}=${newValue}" from ${subformat.name}${subRuleTable.blame(ruleid)} conflicts with "${subSubFormat.mutuallyExclusiveWith}=${ruleTable.valueRules.get(subSubFormat.mutuallyExclusiveWith)}"${ruleTable.blame(subSubFormat.mutuallyExclusiveWith)} (Repeal one with ! before adding another)`);
}
if (newValue !== oldValue) {
if (oldValue !== void 0) {
throw new Error(`Rule "${ruleid}=${newValue}" from ${subformat.name}${subRuleTable.blame(ruleid)} conflicts with "${ruleid}=${oldValue}"${ruleTable.blame(ruleid)} (Repeal one with ! before adding another)`);
}
ruleTable.valueRules.set(ruleid, newValue);
}
}
ruleTable.set(ruleid, sourceFormat || subformat.name);
}
}
for (const [subRule, source, limit, bans] of subRuleTable.complexBans) {
ruleTable.addComplexBan(subRule, source || subformat.name, limit, bans);
}
for (const [subRule, source, limit, bans] of subRuleTable.complexTeamBans) {
ruleTable.addComplexTeamBan(subRule, source || subformat.name, limit, bans);
}
if (subRuleTable.checkCanLearn) {
if (ruleTable.checkCanLearn) {
throw new Error(
`"${format.name}" has conflicting move validation rules from "${ruleTable.checkCanLearn[1]}" and "${subRuleTable.checkCanLearn[1]}"`
);
}
ruleTable.checkCanLearn = subRuleTable.checkCanLearn;
}
if (subRuleTable.timer) {
if (ruleTable.timer) {
throw new Error(
`"${format.name}" has conflicting timer validation rules from "${ruleTable.timer[1]}" and "${subRuleTable.timer[1]}"`
);
}
ruleTable.timer = subRuleTable.timer;
}
}
ruleTable.getTagRules();
ruleTable.resolveNumbers(format, this.dex);
const canMegaEvo = this.dex.gen <= 7 || ruleTable.has("+pokemontag:past");
if (ruleTable.has("obtainableformes") && canMegaEvo && ruleTable.isBannedSpecies(this.dex.species.get("rayquazamega")) && !ruleTable.isBannedSpecies(this.dex.species.get("rayquaza"))) {
ruleTable.set("megarayquazaclause", "");
}
for (const rule of ruleTable.keys()) {
if ("+*-!".includes(rule.charAt(0)))
continue;
const subFormat = this.dex.formats.get(rule);
if (subFormat.exists) {
const value = subFormat.onValidateRule?.call({ format, ruleTable, dex: this.dex }, ruleTable.valueRules.get(rule));
if (typeof value === "string")
ruleTable.valueRules.set(subFormat.id, value);
}
}
if (!repeals)
format.ruleTable = ruleTable;
return ruleTable;
}
validateRule(rule, format = null) {
if (rule !== rule.trim())
throw new Error(`Rule "${rule}" should be trimmed`);
switch (rule.charAt(0)) {
case "-":
case "*":
case "+":
if (rule.slice(1).includes(">") || rule.slice(1).includes("+")) {
let buf = rule.slice(1);
const gtIndex = buf.lastIndexOf(">");
let limit = rule.startsWith("+") ? Infinity : 0;
if (gtIndex >= 0 && /^[0-9]+$/.test(buf.slice(gtIndex + 1).trim())) {
if (limit === 0)
limit = parseInt(buf.slice(gtIndex + 1));
buf = buf.slice(0, gtIndex);
}
let checkTeam = buf.includes("++");
const banNames = buf.split(checkTeam ? "++" : "+").map((v) => v.trim());
if (banNames.length === 1 && limit > 0)
checkTeam = true;
const innerRule = banNames.join(checkTeam ? " ++ " : " + ");
const bans = banNames.map((v) => this.validateBanRule(v));
if (checkTeam) {
return ["complexTeamBan", innerRule, "", limit, bans];
}
if (bans.length > 1 || limit > 0) {
return ["complexBan", innerRule, "", limit, bans];
}
throw new Error(`Confusing rule ${rule}`);
}
return rule.charAt(0) + this.validateBanRule(rule.slice(1));
default:
const [ruleName, value] = rule.split("=");
let id = (0, import_dex_data.toID)(ruleName);
const ruleset = this.dex.formats.get(id);
if (!ruleset.exists) {
throw new Error(`Unrecognized rule "${rule}"`);
}
if (typeof value === "string")
id = `${id}=${value.trim()}`;
if (rule.startsWith("!!"))
return `!!${id}`;
if (rule.startsWith("!"))
return `!${id}`;
return id;
}
}
validPokemonTag(tagid) {
const tag = import_tags.Tags.hasOwnProperty(tagid) && import_tags.Tags[tagid];
if (!tag)
return false;
return !!(tag.speciesFilter || tag.genericFilter);
}
validateBanRule(rule) {
let id = (0, import_dex_data.toID)(rule);
if (id === "unreleased")
return "unreleased";
if (id === "nonexistent")
return "nonexistent";
const matches = [];
let matchTypes = ["pokemon", "move", "ability", "item", "nature", "pokemontag"];
for (const matchType of matchTypes) {
if (rule.startsWith(`${matchType}:`)) {
matchTypes = [matchType];
id = id.slice(matchType.length);
break;
}
}
const ruleid = id;
if (this.dex.data.Aliases.hasOwnProperty(id))
id = (0, import_dex_data.toID)(this.dex.data.Aliases[id]);
for (const matchType of matchTypes) {
if (matchType === "item" && ruleid === "noitem")
return "item:noitem";
let table;
switch (matchType) {
case "pokemon":
table = this.dex.data.Pokedex;
break;
case "move":
table = this.dex.data.Moves;
break;
case "item":
table = this.dex.data.Items;
break;
case "ability":
table = this.dex.data.Abilities;
break;
case "nature":
table = this.dex.data.Natures;
break;
case "pokemontag":
const validTags = [
// all
"allpokemon",
"allitems",
"allmoves",
"allabilities",
"allnatures"
];
if (validTags.includes(ruleid) || this.validPokemonTag(ruleid)) {
matches.push("pokemontag:" + ruleid);
}
continue;
default:
throw new Error(`Unrecognized match type.`);
}
if (table.hasOwnProperty(id)) {
if (matchType === "pokemon") {
const species = table[id];
if ((species.otherFormes || species.cosmeticFormes) && ruleid !== species.id + (0, import_dex_data.toID)(species.baseForme)) {
matches.push("basepokemon:" + id);
continue;
}
}
matches.push(matchType + ":" + id);
} else if (matchType === "pokemon" && id.endsWith("base")) {
id = id.slice(0, -4);
if (table.hasOwnProperty(id)) {
matches.push("pokemon:" + id);
}
}
}
if (matches.length > 1) {
throw new Error(`More than one thing matches "${rule}"; please specify one of: ` + matches.join(", "));
}
if (matches.length < 1) {
throw new Error(`Nothing matches "${rule}"`);
}
return matches[0];
}
}
//# sourceMappingURL=dex-formats.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-formats.ts"],
"sourcesContent": ["import {Utils} from '../lib';\r\nimport {toID, BasicEffect} from './dex-data';\r\nimport {EventMethods} from './dex-conditions';\r\nimport {Tags} from '../data/tags';\r\n\r\nconst DEFAULT_MOD = 'gen9';\r\n\r\nexport interface FormatData extends Partial<Format>, EventMethods {\r\n\tname: string;\r\n}\r\n\r\nexport type FormatList = (FormatData | {section: string, column?: number})[];\r\nexport type ModdedFormatData = FormatData | Omit<FormatData, 'name'> & {inherit: true};\r\n\r\ntype FormatEffectType = 'Format' | 'Ruleset' | 'Rule' | 'ValidatorRule';\r\n\r\n/** rule, source, limit, bans */\r\nexport type ComplexBan = [string, string, number, string[]];\r\nexport type ComplexTeamBan = ComplexBan;\r\n\r\n/**\r\n * A RuleTable keeps track of the rules that a format has. The key can be:\r\n * - '[ruleid]' the ID of a rule in effect\r\n * - '-[thing]' or '-[category]:[thing]' ban a thing\r\n * - '+[thing]' or '+[category]:[thing]' allow a thing (override a ban)\r\n * [category] is one of: item, move, ability, species, basespecies\r\n *\r\n * The value is the name of the parent rule (blank for the active format).\r\n */\r\nexport class RuleTable extends Map<string, string> {\r\n\tcomplexBans: ComplexBan[];\r\n\tcomplexTeamBans: ComplexTeamBan[];\r\n\tcheckCanLearn: [TeamValidator['checkCanLearn'], string] | null;\r\n\ttimer: [Partial<GameTimerSettings>, string] | null;\r\n\ttagRules: string[];\r\n\tvalueRules: Map<string, string>;\r\n\r\n\tminTeamSize!: number;\r\n\tmaxTeamSize!: number;\r\n\tpickedTeamSize!: number | null;\r\n\tmaxTotalLevel!: number | null;\r\n\tmaxMoveCount!: number;\r\n\tminSourceGen!: number;\r\n\tminLevel!: number;\r\n\tmaxLevel!: number;\r\n\tdefaultLevel!: number;\r\n\tadjustLevel!: number | null;\r\n\tadjustLevelDown!: number | null;\r\n\tevLimit!: number | null;\r\n\r\n\tconstructor() {\r\n\t\tsuper();\r\n\t\tthis.complexBans = [];\r\n\t\tthis.complexTeamBans = [];\r\n\t\tthis.checkCanLearn = null;\r\n\t\tthis.timer = null;\r\n\t\tthis.tagRules = [];\r\n\t\tthis.valueRules = new Map();\r\n\t}\r\n\r\n\tisBanned(thing: string) {\r\n\t\tif (this.has(`+${thing}`)) return false;\r\n\t\treturn this.has(`-${thing}`);\r\n\t}\r\n\r\n\tisBannedSpecies(species: Species) {\r\n\t\tif (this.has(`+pokemon:${species.id}`)) return false;\r\n\t\tif (this.has(`-pokemon:${species.id}`)) return true;\r\n\t\tif (this.has(`+basepokemon:${toID(species.baseSpecies)}`)) return false;\r\n\t\tif (this.has(`-basepokemon:${toID(species.baseSpecies)}`)) return true;\r\n\t\tfor (const tagid in Tags) {\r\n\t\t\tconst tag = Tags[tagid];\r\n\t\t\tif (this.has(`-pokemontag:${tagid}`)) {\r\n\t\t\t\tif ((tag.speciesFilter || tag.genericFilter)!(species)) return true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (const tagid in Tags) {\r\n\t\t\tconst tag = Tags[tagid];\r\n\t\t\tif (this.has(`+pokemontag:${tagid}`)) {\r\n\t\t\t\tif ((tag.speciesFilter || tag.genericFilter)!(species)) return false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.has(`-pokemontag:allpokemon`);\r\n\t}\r\n\r\n\tisRestricted(thing: string) {\r\n\t\tif (this.has(`+${thing}`)) return false;\r\n\t\treturn this.has(`*${thing}`);\r\n\t}\r\n\r\n\tisRestrictedSpecies(species: Species) {\r\n\t\tif (this.has(`+pokemon:${species.id}`)) return false;\r\n\t\tif (this.has(`*pokemon:${species.id}`)) return true;\r\n\t\tif (this.has(`+basepokemon:${toID(species.baseSpecies)}`)) return false;\r\n\t\tif (this.has(`*basepokemon:${toID(species.baseSpecies)}`)) return true;\r\n\t\tfor (const tagid in Tags) {\r\n\t\t\tconst tag = Tags[tagid];\r\n\t\t\tif (this.has(`*pokemontag:${tagid}`)) {\r\n\t\t\t\tif ((tag.speciesFilter || tag.genericFilter)!(species)) return true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (const tagid in Tags) {\r\n\t\t\tconst tag = Tags[tagid];\r\n\t\t\tif (this.has(`+pokemontag:${tagid}`)) {\r\n\t\t\t\tif ((tag.speciesFilter || tag.genericFilter)!(species)) return false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.has(`*pokemontag:allpokemon`);\r\n\t}\r\n\r\n\tgetTagRules() {\r\n\t\tconst tagRules = [];\r\n\t\tfor (const ruleid of this.keys()) {\r\n\t\t\tif (/^[+*-]pokemontag:/.test(ruleid)) {\r\n\t\t\t\tconst banid = ruleid.slice(12);\r\n\t\t\t\tif (\r\n\t\t\t\t\tbanid === 'allpokemon' || banid === 'allitems' || banid === 'allmoves' ||\r\n\t\t\t\t\tbanid === 'allabilities' || banid === 'allnatures'\r\n\t\t\t\t) {\r\n\t\t\t\t\t// hardcoded and not a part of the ban rule system\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttagRules.push(ruleid);\r\n\t\t\t\t}\r\n\t\t\t} else if ('+*-'.includes(ruleid.charAt(0)) && ruleid.slice(1) === 'nonexistent') {\r\n\t\t\t\ttagRules.push(ruleid.charAt(0) + 'pokemontag:nonexistent');\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.tagRules = tagRules.reverse();\r\n\t\treturn this.tagRules;\r\n\t}\r\n\r\n\t/**\r\n\t * - non-empty string: banned, string is the reason\r\n\t * - '': whitelisted\r\n\t * - null: neither whitelisted nor banned\r\n\t */\r\n\tcheck(thing: string, setHas: {[id: string]: true} | null = null) {\r\n\t\tif (this.has(`+${thing}`)) retuLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAoB;AACpB,sBAAg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,IAAI,SAAS,MAAM,QAAQ;AAC9C,WAAK,UAAU,IAAI,MAAM,IAAI,MAAM;AACnC,UAAI,OAAO,QAAQ,cAAc;AAChC,aAAK,UAAU,KAAK,IAAI,UAAU,IAAI,OAAO;AAAA,MAC9C;AAAA,IAGD;AAMA,QAAI,KAAK,cAAc,IAAI;AAC1B,YAAM,IAAI,MAAM,iBAAiB,KAAK,cAAc,KAAK,MAAM,aAAa,8CAA8C;AAAA,IAC3H;AACA,QAAI,KAAK,WAAW,OAAO;AAC1B,YAAM,IAAI,MAAM,aAAa,KAAK,WAAW,KAAK,MAAM,UAAU,gDAAgD;AAAA,IACnH;AACA,QAAI,KAAK,eAAe,IAAI;AAI3B,YAAM,IAAI,MAAM,kBAAkB,KAAK,eAAe,KAAK,MAAM,cAAc,6CAA6C;AAAA,IAC7H;AAEA,QAAI,CAAC,KAAK,cAAc;AAGvB,YAAM,cAAc,KAAK,kBAAkB,KAAK;AAChD,UAAI,KAAK,iBAAiB,KAAK,WAAW,OAAO,KAAK,WAAW,cAAc,KAAK,eAAe;AAClG,aAAK,eAAe;AAAA,MACrB,OAAO;AACN,aAAK,eAAe,KAAK;AAAA,MAC1B;AAAA,IACD;AACA,QAAI,KAAK,eAAe,KAAK,cAAc,qBAAqB;AAC/D,YAAM,IAAI,MAAM,iBAAiB,KAAK,cAAc,KAAK,MAAM,aAAa,sBAAsB,6BAA6B,OAAO,gBLine truncated
"names": []
}
+136
View File
@@ -0,0 +1,136 @@
"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 dex_items_exports = {};
__export(dex_items_exports, {
DexItems: () => DexItems,
Item: () => Item
});
module.exports = __toCommonJS(dex_items_exports);
var import_dex_data = require("./dex-data");
class Item extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
data = this;
this.fullname = `item: ${this.name}`;
this.effectType = "Item";
this.fling = data.fling || void 0;
this.onDrive = data.onDrive || void 0;
this.onMemory = data.onMemory || void 0;
this.megaStone = data.megaStone || void 0;
this.megaEvolves = data.megaEvolves || void 0;
this.zMove = data.zMove || void 0;
this.zMoveType = data.zMoveType || void 0;
this.zMoveFrom = data.zMoveFrom || void 0;
this.itemUser = data.itemUser || void 0;
this.isBerry = !!data.isBerry;
this.ignoreKlutz = !!data.ignoreKlutz;
this.onPlate = data.onPlate || void 0;
this.isGem = !!data.isGem;
this.isPokeball = !!data.isPokeball;
if (!this.gen) {
if (this.num >= 1124) {
this.gen = 9;
} else if (this.num >= 927) {
this.gen = 8;
} else if (this.num >= 689) {
this.gen = 7;
} else if (this.num >= 577) {
this.gen = 6;
} else if (this.num >= 537) {
this.gen = 5;
} else if (this.num >= 377) {
this.gen = 4;
} else {
this.gen = 3;
}
}
if (this.isBerry)
this.fling = { basePower: 10 };
if (this.id.endsWith("plate"))
this.fling = { basePower: 90 };
if (this.onDrive)
this.fling = { basePower: 70 };
if (this.megaStone)
this.fling = { basePower: 80 };
if (this.onMemory)
this.fling = { basePower: 50 };
}
}
class DexItems {
constructor(dex) {
this.itemCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.dex = dex;
}
get(name) {
if (name && typeof name !== "string")
return name;
name = (name || "").trim();
const id = (0, import_dex_data.toID)(name);
return this.getByID(id);
}
getByID(id) {
let item = this.itemCache.get(id);
if (item)
return item;
if (this.dex.data.Aliases.hasOwnProperty(id)) {
item = this.get(this.dex.data.Aliases[id]);
if (item.exists) {
this.itemCache.set(id, item);
}
return item;
}
if (id && !this.dex.data.Items[id] && this.dex.data.Items[id + "berry"]) {
item = this.getByID(id + "berry");
this.itemCache.set(id, item);
return item;
}
if (id && this.dex.data.Items.hasOwnProperty(id)) {
const itemData = this.dex.data.Items[id];
const itemTextData = this.dex.getDescs("Items", id, itemData);
item = new Item({
name: id,
...itemData,
...itemTextData
});
if (item.gen > this.dex.gen) {
item.isNonstandard = "Future";
}
if (this.dex.currentMod === "gen7letsgo" && !item.isNonstandard && !item.megaStone) {
item.isNonstandard = "Past";
}
} else {
item = new Item({ name: id, exists: false });
}
if (item.exists)
this.itemCache.set(id, item);
return item;
}
all() {
if (this.allCache)
return this.allCache;
const items = [];
for (const id in this.dex.data.Items) {
items.push(this.getByID(id));
}
this.allCache = items;
return this.allCache;
}
}
//# sourceMappingURL=dex-items.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-items.ts"],
"sourcesContent": ["import {PokemonEventMethods} from './dex-conditions';\r\nimport {BasicEffect, toID} from './dex-data';\r\n\r\ninterface FlingData {\r\n\tbasePower: number;\r\n\tstatus?: string;\r\n\tvolatileStatus?: string;\r\n\teffect?: CommonHandlers['ResultMove'];\r\n}\r\n\r\nexport interface ItemData extends Partial<Item>, PokemonEventMethods {\r\n\tname: string;\r\n}\r\n\r\nexport type ModdedItemData = ItemData | Partial<Omit<ItemData, 'name'>> & {\r\n\tinherit: true,\r\n\tonCustap?: (this: Battle, pokemon: Pokemon) => void,\r\n};\r\n\r\nexport class Item extends BasicEffect implements Readonly<BasicEffect> {\r\n\tdeclare readonly effectType: 'Item';\r\n\r\n\t/** just controls location on the item spritesheet */\r\n\tdeclare readonly num: number;\r\n\r\n\t/**\r\n\t * A Move-like object depicting what happens when Fling is used on\r\n\t * this item.\r\n\t */\r\n\treadonly fling?: FlingData;\r\n\t/**\r\n\t * If this is a Drive: The type it turns Techno Blast into.\r\n\t * undefined, if not a Drive.\r\n\t */\r\n\treadonly onDrive?: string;\r\n\t/**\r\n\t * If this is a Memory: The type it turns Multi-Attack into.\r\n\t * undefined, if not a Memory.\r\n\t */\r\n\treadonly onMemory?: string;\r\n\t/**\r\n\t * If this is a mega stone: The name (e.g. Charizard-Mega-X) of the\r\n\t * forme this allows transformation into.\r\n\t * undefined, if not a mega stone.\r\n\t */\r\n\treadonly megaStone?: string;\r\n\t/**\r\n\t * If this is a mega stone: The name (e.g. Charizard) of the\r\n\t * forme this allows transformation from.\r\n\t * undefined, if not a mega stone.\r\n\t */\r\n\treadonly megaEvolves?: string;\r\n\t/**\r\n\t * If this is a Z crystal: true if the Z Crystal is generic\r\n\t * (e.g. Firium Z). If species-specific, the name\r\n\t * (e.g. Inferno Overdrive) of the Z Move this crystal allows\r\n\t * the use of.\r\n\t * undefined, if not a Z crystal.\r\n\t */\r\n\treadonly zMove?: true | string;\r\n\t/**\r\n\t * If this is a generic Z crystal: The type (e.g. Fire) of the\r\n\t * Z Move this crystal allows the use of (e.g. Fire)\r\n\t * undefined, if not a generic Z crystal\r\n\t */\r\n\treadonly zMoveType?: string;\r\n\t/**\r\n\t * If this is a species-specific Z crystal: The name\r\n\t * (e.g. Play Rough) of the move this crystal requires its\r\n\t * holder to know to use its Z move.\r\n\t * undefined, if not a species-specific Z crystal\r\n\t */\r\n\treadonly zMoveFrom?: string;\r\n\t/**\r\n\t * If this is a species-specific Z crystal: An array of the\r\n\t * species of Pokemon that can use this crystal's Z move.\r\n\t * Note that these are the full names, e.g. 'Mimikyu-Busted'\r\n\t * undefined, if not a species-specific Z crystal\r\n\t */\r\n\treadonly itemUser?: string[];\r\n\t/** Is this item a Berry? */\r\n\treadonly isBerry: boolean;\r\n\t/** Whether or not this item ignores the Klutz ability. */\r\n\treadonly ignoreKlutz: boolean;\r\n\t/** The type the holder will change into if it is an Arceus. */\r\n\treadonly onPlate?: string;\r\n\t/** Is this item a Gem? */\r\n\treadonly isGem: boolean;\r\n\t/** Is this item a Pokeball? */\r\n\treadonly isPokeball: boolean;\r\n\r\n\tdeclare readonly condition?: ConditionData;\r\n\tdeclare readonly forcedForme?: string;\r\n\tdeclare readonly isChoice?: boolean;\r\n\tdeclare readonly naturalGift?: {basePower: number, type: string};\r\n\tdeclare readonly spritenum?: number;\r\n\tdeclare readonly boosts?: SparseBoostsTable | false;\r\n\r\n\tdeclare readonly onEat?: ((this: Battle, pokemon: Pokemon) => void) | false;\r\n\tdeclare readonly onPrimal?: (this: Battle, pokemon: Pokemon) => void;\r\n\tdeclare readonly onStart?: (this: Battle, target: Pokemon) => void;\r\n\tdeclare readonly onEnd?: (this: Battle, target: Pokemon) => void;\r\n\r\n\tconstructor(data: AnyObject) {\r\n\t\tsuper(data);\r\n\t\t// eslint-disable-next-line @typescript-eslint/no-this-alias\r\n\t\tdata = this;\r\n\r\n\t\tthis.fullname = `item: ${this.name}`;\r\n\t\tthis.effectType = 'Item';\r\n\t\tthis.fling = data.fling || undefined;\r\n\t\tthis.onDrive = data.onDrive || undefined;\r\n\t\tthis.onMemory = data.onMemory || undefined;\r\n\t\tthis.megaStone = data.megaStone || undefined;\r\n\t\tthis.megaEvolves = data.megaEvolves || undefined;\r\n\t\tthis.zMove = data.zMove || undefined;\r\n\t\tthis.zMoveType = data.zMoveType || undefined;\r\n\t\tthis.zMoveFrom = data.zMoveFrom || undefined;\r\n\t\tthis.itemUser = data.itemUser || undefined;\r\n\t\tthis.isBerry = !!data.isBerry;\r\n\t\tthis.ignoreKlutz = !!data.ignoreKlutz;\r\n\t\tthis.onPlate = data.onPlate || undefined;\r\n\t\tthis.isGem = !!data.isGem;\r\n\t\tthis.isPokeball = !!data.isPokeball;\r\n\r\n\t\tif (!this.gen) {\r\n\t\t\tif (this.num >= 1124) {\r\n\t\t\t\tthis.gen = 9;\r\n\t\t\t} else if (this.num >= 927) {\r\n\t\t\t\tthis.gen = 8;\r\n\t\t\t} else if (this.num >= 689) {\r\n\t\t\t\tthis.gen = 7;\r\n\t\t\t} else if (this.num >= 577) {\r\n\t\t\t\tthis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AAI,KAAK;AAAA,QACf,MAAM;AAAA,QACN,GAAG;AAAA,QACH,GAAG;AAAA,MACJ,CAAC;AACD,UAAI,KAAK,MAAM,KAAK,IAAI,KAAK;AAC5B,QAAC,KAAa,gBAAgB;AAAA,MAC/B;AAEA,UAAI,KAAK,IAAI,eAAe,gBAAgB,CAAC,KAAK,iBAAiB,CAAC,KAAK,WAAW;AACnF,QAAC,KAAa,gBAAgB;AAAA,MAC/B;AAAA,IACD,OAAO;AACN,aAAO,IAAI,KAAK,EAAC,MAAM,IAAI,QAAQ,MAAK,CAAC;AAAA,IAC1C;AAEA,QAAI,KAAK;AAAQ,WAAK,UAAU,IAAI,IAAI,IAAI;AAC5C,WAAO;AAAA,EACR;AAAA,EAEA,MAAuB;AACtB,QAAI,KAAK;AAAU,aAAO,KAAK;AAC/B,UAAM,QAAQ,CAAC;AACf,eAAW,MAAM,KAAK,IAAI,KAAK,OAAO;AACrC,YAAM,KAAK,KAAK,QAAQ,EAAQ,CAAC;AAAA,IAClC;AACA,SAAK,WAAW;AAChB,WAAO,KAAK;AAAA,EACb;AACD;",
"names": []
}
+218
View File
@@ -0,0 +1,218 @@
"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 dex_moves_exports = {};
__export(dex_moves_exports, {
DataMove: () => DataMove,
DexMoves: () => DexMoves
});
module.exports = __toCommonJS(dex_moves_exports);
var import_lib = require("../lib");
var import_dex_data = require("./dex-data");
class DataMove extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
data = this;
this.fullname = `move: ${this.name}`;
this.effectType = "Move";
this.type = import_lib.Utils.getString(data.type);
this.target = data.target;
this.basePower = Number(data.basePower);
this.accuracy = data.accuracy;
this.critRatio = Number(data.critRatio) || 1;
this.baseMoveType = import_lib.Utils.getString(data.baseMoveType) || this.type;
this.secondary = data.secondary || null;
this.secondaries = data.secondaries || this.secondary && [this.secondary] || null;
this.hasSheerForce = !!(data.hasSheerForce && !this.secondaries);
this.priority = Number(data.priority) || 0;
this.category = data.category;
this.overrideOffensiveStat = data.overrideOffensiveStat || void 0;
this.overrideOffensivePokemon = data.overrideOffensivePokemon || void 0;
this.overrideDefensiveStat = data.overrideDefensiveStat || void 0;
this.overrideDefensivePokemon = data.overrideDefensivePokemon || void 0;
this.ignoreNegativeOffensive = !!data.ignoreNegativeOffensive;
this.ignorePositiveDefensive = !!data.ignorePositiveDefensive;
this.ignoreOffensive = !!data.ignoreOffensive;
this.ignoreDefensive = !!data.ignoreDefensive;
this.ignoreImmunity = data.ignoreImmunity !== void 0 ? data.ignoreImmunity : this.category === "Status";
this.pp = Number(data.pp);
this.noPPBoosts = !!data.noPPBoosts;
this.isZ = data.isZ || false;
this.isMax = data.isMax || false;
this.flags = data.flags || {};
this.selfSwitch = (typeof data.selfSwitch === "string" ? data.selfSwitch : data.selfSwitch) || void 0;
this.pressureTarget = data.pressureTarget || "";
this.nonGhostTarget = data.nonGhostTarget || "";
this.ignoreAbility = data.ignoreAbility || false;
this.damage = data.damage;
this.spreadHit = data.spreadHit || false;
this.forceSTAB = !!data.forceSTAB;
this.noSketch = !!data.noSketch;
this.stab = data.stab || void 0;
this.volatileStatus = typeof data.volatileStatus === "string" ? data.volatileStatus : void 0;
if (this.category !== "Status" && !this.maxMove && this.id !== "struggle") {
this.maxMove = { basePower: 1 };
if (this.isMax || this.isZ) {
} else if (!this.basePower) {
this.maxMove.basePower = 100;
} else if (["Fighting", "Poison"].includes(this.type)) {
if (this.basePower >= 150) {
this.maxMove.basePower = 100;
} else if (this.basePower >= 110) {
this.maxMove.basePower = 95;
} else if (this.basePower >= 75) {
this.maxMove.basePower = 90;
} else if (this.basePower >= 65) {
this.maxMove.basePower = 85;
} else if (this.basePower >= 55) {
this.maxMove.basePower = 80;
} else if (this.basePower >= 45) {
this.maxMove.basePower = 75;
} else {
this.maxMove.basePower = 70;
}
} else {
if (this.basePower >= 150) {
this.maxMove.basePower = 150;
} else if (this.basePower >= 110) {
this.maxMove.basePower = 140;
} else if (this.basePower >= 75) {
this.maxMove.basePower = 130;
} else if (this.basePower >= 65) {
this.maxMove.basePower = 120;
} else if (this.basePower >= 55) {
this.maxMove.basePower = 110;
} else if (this.basePower >= 45) {
this.maxMove.basePower = 100;
} else {
this.maxMove.basePower = 90;
}
}
}
if (this.category !== "Status" && !this.zMove && !this.isZ && !this.isMax && this.id !== "struggle") {
let basePower = this.basePower;
this.zMove = {};
if (Array.isArray(this.multihit))
basePower *= 3;
if (!basePower) {
this.zMove.basePower = 100;
} else if (basePower >= 140) {
this.zMove.basePower = 200;
} else if (basePower >= 130) {
this.zMove.basePower = 195;
} else if (basePower >= 120) {
this.zMove.basePower = 190;
} else if (basePower >= 110) {
this.zMove.basePower = 185;
} else if (basePower >= 100) {
this.zMove.basePower = 180;
} else if (basePower >= 90) {
this.zMove.basePower = 175;
} else if (basePower >= 80) {
this.zMove.basePower = 160;
} else if (basePower >= 70) {
this.zMove.basePower = 140;
} else if (basePower >= 60) {
this.zMove.basePower = 120;
} else {
this.zMove.basePower = 100;
}
}
if (!this.gen) {
if (this.num >= 827 && !this.isMax) {
this.gen = 9;
} else if (this.num >= 743) {
this.gen = 8;
} else if (this.num >= 622) {
this.gen = 7;
} else if (this.num >= 560) {
this.gen = 6;
} else if (this.num >= 468) {
this.gen = 5;
} else if (this.num >= 355) {
this.gen = 4;
} else if (this.num >= 252) {
this.gen = 3;
} else if (this.num >= 166) {
this.gen = 2;
} else if (this.num >= 1) {
this.gen = 1;
}
}
}
}
class DexMoves {
constructor(dex) {
this.moveCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.dex = dex;
}
get(name) {
if (name && typeof name !== "string")
return name;
name = (name || "").trim();
const id = (0, import_dex_data.toID)(name);
return this.getByID(id);
}
getByID(id) {
let move = this.moveCache.get(id);
if (move)
return move;
if (this.dex.data.Aliases.hasOwnProperty(id)) {
move = this.get(this.dex.data.Aliases[id]);
if (move.exists) {
this.moveCache.set(id, move);
}
return move;
}
if (id.startsWith("hiddenpower")) {
id = /([a-z]*)([0-9]*)/.exec(id)[1];
}
if (id && this.dex.data.Moves.hasOwnProperty(id)) {
const moveData = this.dex.data.Moves[id];
const moveTextData = this.dex.getDescs("Moves", id, moveData);
move = new DataMove({
name: id,
...moveData,
...moveTextData
});
if (move.gen > this.dex.gen) {
move.isNonstandard = "Future";
}
} else {
move = new DataMove({
name: id,
exists: false
});
}
if (move.exists)
this.moveCache.set(id, move);
return move;
}
all() {
if (this.allCache)
return this.allCache;
const moves = [];
for (const id in this.dex.data.Moves) {
moves.push(this.getByID(id));
}
this.allCache = moves;
return this.allCache;
}
}
//# sourceMappingURL=dex-moves.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-moves.ts"],
"sourcesContent": ["import {Utils} from '../lib';\r\nimport {BasicEffect, toID} from './dex-data';\r\n\r\n/**\r\n * Describes the acceptable target(s) of a move.\r\n * adjacentAlly - Only relevant to Doubles or Triples, the move only targets an ally of the user.\r\n * adjacentAllyOrSelf - The move can target the user or its ally.\r\n * adjacentFoe - The move can target a foe, but not (in Triples) a distant foe.\r\n * all - The move targets the field or all Pok\u00E9mon at once.\r\n * allAdjacent - The move is a spread move that also hits the user's ally.\r\n * allAdjacentFoes - The move is a spread move.\r\n * allies - The move affects all active Pok\u00E9mon on the user's team.\r\n * allySide - The move adds a side condition on the user's side.\r\n * allyTeam - The move affects all unfainted Pok\u00E9mon on the user's team.\r\n * any - The move can hit any other active Pok\u00E9mon, not just those adjacent.\r\n * foeSide - The move adds a side condition on the foe's side.\r\n * normal - The move can hit one adjacent Pok\u00E9mon of your choice.\r\n * randomNormal - The move targets an adjacent foe at random.\r\n * scripted - The move targets the foe that damaged the user.\r\n * self - The move affects the user of the move.\r\n */\r\nexport type MoveTarget =\r\n\t'adjacentAlly' | 'adjacentAllyOrSelf' | 'adjacentFoe' | 'all' | 'allAdjacent' | 'allAdjacentFoes' |\r\n\t'allies' | 'allySide' | 'allyTeam' | 'any' | 'foeSide' | 'normal' | 'randomNormal' | 'scripted' | 'self';\r\n\r\n/** Possible move flags. */\r\ninterface MoveFlags {\r\n\tallyanim?: 1; // The move plays its animation when used on an ally.\r\n\tbypasssub?: 1; // Ignores a target's substitute.\r\n\tbite?: 1; // Power is multiplied by 1.5 when used by a Pokemon with the Ability Strong Jaw.\r\n\tbullet?: 1; // Has no effect on Pokemon with the Ability Bulletproof.\r\n\tcharge?: 1; // The user is unable to make a move between turns.\r\n\tcontact?: 1; // Makes contact.\r\n\tdance?: 1; // When used by a Pokemon, other Pokemon with the Ability Dancer can attempt to execute the same move.\r\n\tdefrost?: 1; // Thaws the user if executed successfully while the user is frozen.\r\n\tdistance?: 1; // Can target a Pokemon positioned anywhere in a Triple Battle.\r\n\tfailcopycat?: 1; // Cannot be selected by Copycat.\r\n\tfailencore?: 1; // Encore fails if target used this move.\r\n\tfailinstruct?: 1; // Cannot be repeated by Instruct.\r\n\tfailmefirst?: 1; // Cannot be selected by Me First.\r\n\tfailmimic?: 1; // Cannot be copied by Mimic.\r\n\tfuturemove?: 1; // Targets a slot, and in 2 turns damages that slot.\r\n\tgravity?: 1; // Prevented from being executed or selected during Gravity's effect.\r\n\theal?: 1; // Prevented from being executed or selected during Heal Block's effect.\r\n\tmirror?: 1; // Can be copied by Mirror Move.\r\n\tmustpressure?: 1; // Additional PP is deducted due to Pressure when it ordinarily would not.\r\n\tnoassist?: 1; // Cannot be selected by Assist.\r\n\tnonsky?: 1; // Prevented from being executed or selected in a Sky Battle.\r\n\tnoparentalbond?: 1; // Cannot be made to hit twice via Parental Bond.\r\n\tnosleeptalk?: 1; // Cannot be selected by Sleep Talk.\r\n\tpledgecombo?: 1; // Gems will not activate. Cannot be redirected by Storm Drain / Lightning Rod.\r\n\tpowder?: 1; // Has no effect on Pokemon which are Grass-type, have the Ability Overcoat, or hold Safety Goggles.\r\n\tprotect?: 1; // Blocked by Detect, Protect, Spiky Shield, and if not a Status move, King's Shield.\r\n\tpulse?: 1; // Power is multiplied by 1.5 when used by a Pokemon with the Ability Mega Launcher.\r\n\tpunch?: 1; // Power is multiplied by 1.2 when used by a Pokemon with the Ability Iron Fist.\r\n\trecharge?: 1; // If this move is successful, the user must recharge on the following turn and cannot make a move.\r\n\treflectable?: 1; // Bounced back to the original user by Magic Coat or the Ability Magic Bounce.\r\n\tslicing?: 1; // Power is multiplied by 1.5 when used by a Pokemon with the Ability Sharpness.\r\n\tsnatch?: 1; // Can be stolen from the original user and instead used by another Pokemon using Snatch.\r\n\tsound?: 1; // Has no effect on Pokemon with the Ability Soundproof.\r\n\twind?: 1; // Activates the Wind Power and Wind Rider Abilities.\r\n}\r\n\r\nexport interface HitEffect {\r\n\tonHit?: MoveEventMethods['onHit'];\r\n\r\n\t// set pokemon conditions\r\n\tboosts?: SparseBoostsTable | null;\r\n\tstatus?: string;\r\n\tvolatileStatus?: string;\r\n\r\n\t// set side/slot conditions\r\n\tsideCondition?: string;\r\n\tslotCondition?: string;\r\n\r\n\t// set field conditions\r\n\tpseudoWeather?: string;\r\n\tterrain?: string;\r\n\tweather?: string;\r\n}\r\n\r\nexport interface SecondaryEffect extends HitEffect {\r\n\tchance?: number;\r\n\t/** Used to flag a secondary effect as added by Poison Touch */\r\n\tability?: Ability;\r\n\t/**\r\n\t * Applies to Sparkling Aria's secondary effect: Affected by\r\n\t * Sheer Force but not Shield Dust.\r\n\Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AA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AM,EAAE;AACvC,YAAM,eAAe,KAAK,IAAI,SAAS,SAAS,IAAI,QAAQ;AAC5D,aAAO,IAAI,SAAS;AAAA,QACnB,MAAM;AAAA,QACN,GAAG;AAAA,QACH,GAAG;AAAA,MACJ,CAAC;AACD,UAAI,KAAK,MAAM,KAAK,IAAI,KAAK;AAC5B,QAAC,KAAa,gBAAgB;AAAA,MAC/B;AAAA,IACD,OAAO;AACN,aAAO,IAAI,SAAS;AAAA,QACnB,MAAM;AAAA,QAAI,QAAQ;AAAA,MACnB,CAAC;AAAA,IACF;AACA,QAAI,KAAK;AAAQ,WAAK,UAAU,IAAI,IAAI,IAAI;AAC5C,WAAO;AAAA,EACR;AAAA,EAEA,MAAuB;AACtB,QAAI,KAAK;AAAU,aAAO,KAAK;AAC/B,UAAM,QAAQ,CAAC;AACf,eAAW,MAAM,KAAK,IAAI,KAAK,OAAO;AACrC,YAAM,KAAK,KAAK,QAAQ,EAAQ,CAAC;AAAA,IAClC;AACA,SAAK,WAAW;AAChB,WAAO,KAAK;AAAA,EACb;AACD;",
"names": []
}
+326
View File
@@ -0,0 +1,326 @@
"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 dex_species_exports = {};
__export(dex_species_exports, {
DexSpecies: () => DexSpecies,
Learnset: () => Learnset,
Species: () => Species
});
module.exports = __toCommonJS(dex_species_exports);
var import_dex_data = require("./dex-data");
var CobblemonCache = __toESM(require("./cobblemon-cache"));
class Species extends import_dex_data.BasicEffect {
constructor(data) {
super(data);
data = this;
this.fullname = `pokemon: ${data.name}`;
this.effectType = "Pokemon";
this.baseSpecies = data.baseSpecies || this.name;
this.forme = data.forme || "";
this.baseForme = data.baseForme || "";
this.cosmeticFormes = data.cosmeticFormes || void 0;
this.otherFormes = data.otherFormes || void 0;
this.formeOrder = data.formeOrder || void 0;
this.spriteid = data.spriteid || (0, import_dex_data.toID)(this.baseSpecies) + (this.baseSpecies !== this.name ? `-${(0, import_dex_data.toID)(this.forme)}` : "");
this.abilities = data.abilities || { 0: "" };
this.types = data.types || ["???"];
this.addedType = data.addedType || void 0;
this.prevo = data.prevo || "";
this.tier = data.tier || "";
this.doublesTier = data.doublesTier || "";
this.natDexTier = data.natDexTier || "";
this.evos = data.evos || [];
this.evoType = data.evoType || void 0;
this.evoMove = data.evoMove || void 0;
this.evoLevel = data.evoLevel || void 0;
this.nfe = data.nfe || false;
this.eggGroups = data.eggGroups || [];
this.canHatch = data.canHatch || false;
this.gender = data.gender || "";
this.genderRatio = data.genderRatio || (this.gender === "M" ? { M: 1, F: 0 } : this.gender === "F" ? { M: 0, F: 1 } : this.gender === "N" ? { M: 0, F: 0 } : { M: 0.5, F: 0.5 });
this.requiredItem = data.requiredItem || void 0;
this.requiredItems = this.requiredItems || (this.requiredItem ? [this.requiredItem] : void 0);
this.baseStats = data.baseStats || { hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0 };
this.bst = this.baseStats.hp + this.baseStats.atk + this.baseStats.def + this.baseStats.spa + this.baseStats.spd + this.baseStats.spe;
this.weightkg = data.weightkg || 0;
this.weighthg = this.weightkg * 10;
this.heightm = data.heightm || 0;
this.color = data.color || "";
this.tags = data.tags || [];
this.unreleasedHidden = data.unreleasedHidden || false;
this.maleOnlyHidden = !!data.maleOnlyHidden;
this.maxHP = data.maxHP || void 0;
this.isMega = !!(this.forme && ["Mega", "Mega-X", "Mega-Y"].includes(this.forme)) || void 0;
this.canGigantamax = data.canGigantamax || void 0;
this.gmaxUnreleased = !!data.gmaxUnreleased;
this.cannotDynamax = !!data.cannotDynamax;
this.battleOnly = data.battleOnly || (this.isMega ? this.baseSpecies : void 0);
this.changesFrom = data.changesFrom || (this.battleOnly !== this.baseSpecies ? this.battleOnly : this.baseSpecies);
if (Array.isArray(data.changesFrom))
this.changesFrom = data.changesFrom[0];
if (!this.gen && this.num >= 1) {
if (this.num >= 906 || this.forme.includes("Paldea")) {
this.gen = 9;
} else if (this.num >= 810 || ["Gmax", "Galar", "Galar-Zen", "Hisui"].includes(this.forme)) {
this.gen = 8;
} else if (this.num >= 722 || this.forme.startsWith("Alola") || this.forme === "Starter") {
this.gen = 7;
} else if (this.forme === "Primal") {
this.gen = 6;
this.isPrimal = true;
this.battleOnly = this.baseSpecies;
} else if (this.num >= 650 || this.isMega) {
this.gen = 6;
} else if (this.num >= 494) {
this.gen = 5;
} else if (this.num >= 387) {
this.gen = 4;
} else if (this.num >= 252) {
this.gen = 3;
} else if (this.num >= 152) {
this.gen = 2;
} else {
this.gen = 1;
}
}
}
}
class Learnset {
constructor(data) {
this.exists = true;
this.effectType = "Learnset";
this.learnset = data.learnset || void 0;
this.eventOnly = !!data.eventOnly;
this.eventData = data.eventData || void 0;
this.encounters = data.encounters || void 0;
}
}
class DexSpecies {
constructor(dex) {
this.speciesCache = /* @__PURE__ */ new Map();
this.learnsetCache = /* @__PURE__ */ new Map();
this.allCache = null;
this.dex = dex;
}
get(name) {
if (name && typeof name !== "string")
return name;
name = (name || "").trim();
let id = (0, import_dex_data.toID)(name);
if (id === "nidoran" && name.endsWith("\u2640")) {
id = "nidoranf";
} else if (id === "nidoran" && name.endsWith("\u2642")) {
id = "nidoranm";
}
return this.getByID(id);
}
getByID(id) {
let species = this.dex.currentMod === CobblemonCache.MOD_ID ? CobblemonCache.speciesByID(id) : this.speciesCache.get(id);
if (species)
return species;
if (this.dex.data.Aliases.hasOwnProperty(id)) {
if (this.dex.data.FormatsData.hasOwnProperty(id)) {
const baseId = (0, import_dex_data.toID)(this.dex.data.Aliases[id]);
species = new Species({
...this.dex.data.Pokedex[baseId],
...this.dex.data.FormatsData[id],
name: id
});
species.abilities = { 0: species.abilities["S"] };
} else {
species = this.get(this.dex.data.Aliases[id]);
if (species.cosmeticFormes) {
for (const forme of species.cosmeticFormes) {
if ((0, import_dex_data.toID)(forme) === id) {
species = new Species({
...species,
name: forme,
forme: forme.slice(species.name.length + 1),
baseForme: "",
baseSpecies: species.name,
otherFormes: null,
cosmeticFormes: null
});
break;
}
}
}
}
this.speciesCache.set(id, species);
return species;
}
if (!this.dex.data.Pokedex.hasOwnProperty(id)) {
let aliasTo = "";
const formeNames = {
alola: ["a", "alola", "alolan"],
galar: ["g", "galar", "galarian"],
hisui: ["h", "hisui", "hisuian"],
paldea: ["p", "paldea", "paldean"],
mega: ["m", "mega"],
primal: ["p", "primal"]
};
for (const forme in formeNames) {
let pokeName = "";
for (const i of formeNames[forme]) {
if (id.startsWith(i)) {
pokeName = id.slice(i.length);
} else if (id.endsWith(i)) {
pokeName = id.slice(0, -i.length);
}
}
if (this.dex.data.Aliases.hasOwnProperty(pokeName))
pokeName = (0, import_dex_data.toID)(this.dex.data.Aliases[pokeName]);
if (this.dex.data.Pokedex[pokeName + forme]) {
aliasTo = pokeName + forme;
break;
}
}
if (aliasTo) {
species = this.get(aliasTo);
if (species.exists) {
this.speciesCache.set(id, species);
return species;
}
}
}
if (id && this.dex.data.Pokedex.hasOwnProperty(id)) {
const pokedexData = this.dex.data.Pokedex[id];
const baseSpeciesTags = pokedexData.baseSpecies && this.dex.data.Pokedex[(0, import_dex_data.toID)(pokedexData.baseSpecies)].tags;
species = new Species({
tags: baseSpeciesTags,
...pokedexData,
...this.dex.data.FormatsData[id]
});
const baseSpeciesStatuses = this.dex.data.Conditions[(0, import_dex_data.toID)(species.baseSpecies)];
if (baseSpeciesStatuses !== void 0) {
let key;
for (key in baseSpeciesStatuses) {
if (!(key in species))
species[key] = baseSpeciesStatuses[key];
}
}
if (!species.tier && !species.doublesTier && !species.natDexTier && species.baseSpecies !== species.name) {
if (species.baseSpecies === "Mimikyu") {
species.tier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.baseSpecies)].tier || "Illegal";
species.doublesTier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.baseSpecies)].doublesTier || "Illegal";
species.natDexTier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.baseSpecies)].natDexTier || "Illegal";
} else if (species.id.endsWith("totem")) {
species.tier = this.dex.data.FormatsData[species.id.slice(0, -5)].tier || "Illegal";
species.doublesTier = this.dex.data.FormatsData[species.id.slice(0, -5)].doublesTier || "Illegal";
species.natDexTier = this.dex.data.FormatsData[species.id.slice(0, -5)].natDexTier || "Illegal";
} else if (species.battleOnly) {
species.tier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.battleOnly)].tier || "Illegal";
species.doublesTier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.battleOnly)].doublesTier || "Illegal";
species.natDexTier = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.battleOnly)].natDexTier || "Illegal";
} else {
const baseFormatsData = this.dex.data.FormatsData[(0, import_dex_data.toID)(species.baseSpecies)];
if (!baseFormatsData) {
throw new Error(`${species.baseSpecies} has no formats-data entry`);
}
species.tier = baseFormatsData.tier || "Illegal";
species.doublesTier = baseFormatsData.doublesTier || "Illegal";
species.natDexTier = baseFormatsData.natDexTier || "Illegal";
}
}
if (!species.tier)
species.tier = "Illegal";
if (!species.doublesTier)
species.doublesTier = species.tier;
if (!species.natDexTier)
species.natDexTier = species.tier;
if (species.gen > this.dex.gen) {
species.tier = "Illegal";
species.doublesTier = "Illegal";
species.natDexTier = "Illegal";
species.isNonstandard = "Future";
}
if (this.dex.currentMod === "gen7letsgo" && !species.isNonstandard) {
const isLetsGo = (species.num <= 151 || ["Meltan", "Melmetal"].includes(species.name)) && (!species.forme || ["Alola", "Mega", "Mega-X", "Mega-Y", "Starter"].includes(species.forme) && species.name !== "Pikachu-Alola");
if (!isLetsGo)
species.isNonstandard = "Past";
}
if (this.dex.currentMod === "gen8bdsp" && (!species.isNonstandard || ["Gigantamax", "CAP"].includes(species.isNonstandard))) {
if (species.gen > 4 || species.num < 1 && species.isNonstandard !== "CAP" || species.id === "pichuspikyeared") {
species.isNonstandard = "Future";
species.tier = species.doublesTier = species.natDexTier = "Illegal";
}
}
species.nfe = species.evos.some((evo) => {
const evoSpecies = this.get(evo);
return !evoSpecies.isNonstandard || evoSpecies.isNonstandard === species?.isNonstandard || // Pokemon with Hisui evolutions
evoSpecies.isNonstandard === "Unobtainable";
});
species.canHatch = species.canHatch || !["Ditto", "Undiscovered"].includes(species.eggGroups[0]) && !species.prevo && species.name !== "Manaphy";
if (this.dex.gen === 1)
species.bst -= species.baseStats.spd;
if (this.dex.gen < 5)
delete species.abilities["H"];
if (this.dex.gen === 3 && this.dex.abilities.get(species.abilities["1"]).gen === 4)
delete species.abilities["1"];
} else {
species = new Species({
id,
name: id,
exists: false,
tier: "Illegal",
doublesTier: "Illegal",
natDexTier: "Illegal",
isNonstandard: "Custom"
});
}
if (species.exists)
this.speciesCache.set(id, species);
return species;
}
getLearnset(id) {
return this.getLearnsetData(id).learnset;
}
getLearnsetData(id) {
let learnsetData = this.learnsetCache.get(id);
if (learnsetData)
return learnsetData;
if (!this.dex.data.Learnsets.hasOwnProperty(id)) {
return new Learnset({ exists: false });
}
learnsetData = new Learnset(this.dex.data.Learnsets[id]);
this.learnsetCache.set(id, learnsetData);
return learnsetData;
}
all() {
if (this.allCache)
return this.allCache;
const species = [];
for (const id in this.dex.data.Pokedex) {
species.push(this.getByID(id));
}
this.allCache = species;
return this.allCache;
}
}
//# sourceMappingURL=dex-species.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex-species.ts"],
"sourcesContent": ["import { toID, BasicEffect } from './dex-data';\r\nimport * as CobblemonCache from './cobblemon-cache';\r\n\r\ninterface SpeciesAbility {\r\n\t0: string;\r\n\t1?: string;\r\n\tH?: string;\r\n\tS?: string;\r\n}\r\n\r\ntype SpeciesTag = \"Mythical\" | \"Restricted Legendary\" | \"Sub-Legendary\" | \"Paradox\";\r\n\r\nexport interface SpeciesData extends Partial<Species> {\r\n\tname: string;\r\n\t/** National Dex number */\r\n\tnum: number;\r\n\r\n\ttypes: string[];\r\n\tabilities: SpeciesAbility;\r\n\tbaseStats: StatsTable;\r\n\teggGroups: string[];\r\n\tweightkg: number;\r\n}\r\n\r\nexport type ModdedSpeciesData = SpeciesData | Partial<Omit<SpeciesData, 'name'>> & {inherit: true};\r\n\r\nexport interface SpeciesFormatsData {\r\n\tdoublesTier?: TierTypes.Doubles | TierTypes.Other;\r\n\tgmaxUnreleased?: boolean;\r\n\tisNonstandard?: Nonstandard | null;\r\n\tnatDexTier?: TierTypes.Singles | TierTypes.Other;\r\n\ttier?: TierTypes.Singles | TierTypes.Other;\r\n}\r\n\r\nexport type ModdedSpeciesFormatsData = SpeciesFormatsData & {inherit?: true};\r\n\r\nexport interface LearnsetData {\r\n\tlearnset?: {[moveid: string]: MoveSource[]};\r\n\teventData?: EventInfo[];\r\n\teventOnly?: boolean;\r\n\tencounters?: EventInfo[];\r\n\texists?: boolean;\r\n}\r\n\r\nexport type ModdedLearnsetData = LearnsetData & {inherit?: true};\r\n\r\nexport class Species extends BasicEffect implements Readonly<BasicEffect & SpeciesFormatsData> {\r\n\tdeclare readonly effectType: 'Pokemon';\r\n\t/**\r\n\t * Species ID. Identical to ID. Note that this is the full ID, e.g.\r\n\t * 'basculinbluestriped'. To get the base species ID, you need to\r\n\t * manually read toID(species.baseSpecies).\r\n\t */\r\n\tdeclare readonly id: ID;\r\n\t/**\r\n\t * Name. Note that this is the full name with forme,\r\n\t * e.g. 'Basculin-Blue-Striped'. To get the name without forme, see\r\n\t * `species.baseSpecies`.\r\n\t */\r\n\tdeclare readonly name: string;\r\n\t/**\r\n\t * Base species. Species, but without the forme name.\r\n\t *\r\n\t * DO NOT ASSUME A POKEMON CAN TRANSFORM FROM `baseSpecies` TO\r\n\t * `species`. USE `changesFrom` FOR THAT.\r\n\t */\r\n\treadonly baseSpecies: string;\r\n\t/**\r\n\t * Forme name. If the forme exists,\r\n\t * `species.name === species.baseSpecies + '-' + species.forme`\r\n\t *\r\n\t * The games make a distinction between Forme (foorumu) (legendary Pok\u00E9mon)\r\n\t * and Form (sugata) (non-legendary Pok\u00E9mon). PS does not use the same\r\n\t * distinction \u2013 they're all \"Forme\" to PS, reflecting current community\r\n\t * use of the term.\r\n\t *\r\n\t * This property only tracks non-cosmetic formes, and will be `''` for\r\n\t * cosmetic formes.\r\n\t */\r\n\treadonly forme: string;\r\n\t/**\r\n\t * Base forme name (e.g. 'Altered' for Giratina).\r\n\t */\r\n\treadonly baseForme: string;\r\n\t/**\r\n\t * Other forms. List of names of cosmetic forms. These should have\r\n\t * `aliases.js` aliases to this entry, but not have their own\r\n\t * entry in `pokedex.js`.\r\n\t */\r\n\treadonly cosmeticFormes?: string[];\r\n\t/**\r\n\t * Other formes. List of names of formes, appears only on the base\r\n\t * forme. Unlike forms, these have their own entry in `pokedex.js`.\r\n\t */\r\n\treadonly otherFormes?: string[];\r\n\t/**\r\n\t * List of forme speciesNames in the order they appear in the game data -\r\n\t * the union of baseSpecies, otherFormes and cosmeticFormes. Appears only on\r\n\t * the base species forme.\r\n\t *\r\n\t * A species's alternate formeindex may change from generation to generation -\r\n\t * the forme with index N in Gen A is not guaranteed to be the same forme as the\r\n\t * forme with index in Gen B.\r\n\t *\r\n\t * Gigantamaxes are not considered formes by the game (see data/FORMES.md - PS\r\n\t * labels them as such for convenience) - Gigantamax \"formes\" are instead included at\r\n\t * the end of the formeOrder list so as not to interfere with the correct index numbers.\r\n\t */\r\n\treadonly formeOrder?: string[];\r\n\t/**\r\n\t * Sprite ID. Basically the same as ID, but with a dash between\r\n\t * species and forme.\r\n\t */\r\n\treadonly spriteid: string;\r\n\t/** Abilities. */\r\n\treadonly abilities: SpeciesAbility;\r\n\t/** Types. */\r\n\treadonly types: string[];\r\n\t/** Added type (added by Trick-Or-Treat or Forest's Curse, but only listed in species by OMs). */\r\n\treadonly addedType?: string;\r\n\t/** Pre-evolution. '' if nothing evolves into this Pokemon. */\r\n\treadonly prevo: string;\r\n\t/** Evolutions. Array because many Pokemon have multiple evolutions. */\r\n\treadonly evos: string[];\r\n\treadonly evoType?: 'trade' | 'useItem' | 'levelMove' | 'levelExtra' | 'levelFriendship' | 'levelHold' | 'other';\r\n\t/** Evolution condition. falsy if doesn't evolve. */\r\n\tdeclare readonly evoCondition?: string;\r\n\t/** Evolution item. falsy if doesn't evolve. */\r\n\tdeclare readonly evoItem?: string;\r\n\t/** Evolution move. falsy if doesn't evolve. */\r\n\treaLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAkC;AAClC,qBAAgC;AA6CzB,MAAM,gBAAgB,4BAAkE;AAAA,EAgL9F,YAAY,MAAiB;AAC5B,UAAM,IAAI;AAEV,WAAO;AAEP,SAAK,WAAW,YAAY,KAAK;AACjC,SAAK,aAAa;AAClB,SAAK,cAAc,KAAK,eAAe,KAAK;AAC5C,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,YAAY,KAAK,aAAa;AACnC,SAAK,iBAAiB,KAAK,kBAAkB;AAC7C,SAAK,cAAc,KAAK,eAAe;AACvC,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,WAAW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C7B,WAAW,GAAG,SAAS,CAAC,GAAG;AAC1B,uBAAW,GAAG,MAAM,GAAG,CAAC,EAAE,MAAM;AAAA,UACjC;AAAA,QACD;AACA,YAAI,KAAK,IAAI,KAAK,QAAQ,eAAe,QAAQ;AAAG,yBAAW,sBAAK,KAAK,IAAI,KAAK,QAAQ,QAAQ,CAAC;AACnG,YAAI,KAAK,IAAI,KAAK,QAAQ,WAAW,KAAK,GAAG;AAC5C,oBAAU,WAAW;AACrB;AAAA,QACD;AAAA,MACD;AACA,UAAI,SAAS;AACZ,kBAAU,KAAK,IAAI,OAAO;AAC1B,YAAI,QAAQ,QAAQ;AACnB,eAAK,aAAa,IAAI,IAAI,OAAO;AACjC,iBAAO;AAAA,QACR;AAAA,MACD;AAAA,IACD;AACA,QAAI,MAAM,KAAK,IAAI,KAAK,QAAQ,eAAe,EAAE,GAAG;AACnLine truncated
"names": []
}
+568
View File
@@ -0,0 +1,568 @@
"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 dex_exports = {};
__export(dex_exports, {
Dex: () => Dex,
ModdedDex: () => ModdedDex,
default: () => dex_default,
toID: () => toID
});
module.exports = __toCommonJS(dex_exports);
var Data = __toESM(require("./dex-data"));
var import_dex_conditions = require("./dex-conditions");
var import_dex_moves = require("./dex-moves");
var import_dex_items = require("./dex-items");
var import_dex_abilities = require("./dex-abilities");
var import_dex_species = require("./dex-species");
var import_dex_formats = require("./dex-formats");
var import_lib = require("../lib");
var CobblemonCache = __toESM(require("./cobblemon-cache"));
/**
* Dex
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Handles getting data about pokemon, items, etc. Also contains some useful
* helper functions for using dex data.
*
* By default, nothing is loaded until you call Dex.mod(mod) or
* Dex.forFormat(format).
*
* You may choose to preload some things:
* - Dex.includeMods() ~10ms
* This will preload `Dex.dexes`, giving you a list of possible mods.
* - Dex.includeFormats() ~30ms
* As above, but will also preload `Dex.formats.all()`.
* - Dex.includeData() ~500ms
* As above, but will also preload all of Dex.data for Gen 8, so
* functions like `Dex.species.get`, etc will be instantly usable.
* - Dex.includeModData() ~1500ms
* As above, but will also preload `Dex.dexes[...].data` for all mods.
*
* Note that preloading is never necessary. All the data will be
* automatically preloaded when needed, preloading will just spend time
* now so you don't need to spend time later.
*
* @license MIT
*/
const BASE_MOD = "gen9";
const DATA_PATH = "../data";
const DATA_DIR = DATA_PATH;
const MODS_DIR = DATA_PATH + "/mods";
const dexes = /* @__PURE__ */ Object.create(null);
const DATA_TYPES = [
"Abilities",
"Rulesets",
"FormatsData",
"Items",
"Learnsets",
"Moves",
"Natures",
"Pokedex",
"Scripts",
"Conditions",
"TypeChart"
];
const DATA_FILES = {
Abilities: "abilities",
Aliases: "aliases",
Rulesets: "rulesets",
FormatsData: "formats-data",
Items: "items",
Learnsets: "learnsets",
Moves: "moves",
Natures: "natures",
Pokedex: "pokedex",
Scripts: "scripts",
Conditions: "conditions",
TypeChart: "typechart"
};
const toID = Data.toID;
class ModdedDex {
constructor(mod = "base") {
this.Data = Data;
this.Condition = import_dex_conditions.Condition;
this.Ability = import_dex_abilities.Ability;
this.Item = import_dex_items.Item;
this.Move = import_dex_moves.DataMove;
this.Species = import_dex_species.Species;
this.Format = import_dex_formats.Format;
this.ModdedDex = ModdedDex;
this.name = "[ModdedDex]";
this.toID = Data.toID;
this.gen = 0;
this.parentMod = "";
this.modsLoaded = false;
this.deepClone = import_lib.Utils.deepClone;
this.isBase = mod === "base";
this.currentMod = mod;
this.dataDir = this.isBase ? DATA_DIR : MODS_DIR + "/" + this.currentMod;
this.dataCache = null;
this.textCache = null;
this.formats = new import_dex_formats.DexFormats(this);
this.abilities = new import_dex_abilities.DexAbilities(this);
this.items = new import_dex_items.DexItems(this);
this.moves = new import_dex_moves.DexMoves(this);
this.species = new import_dex_species.DexSpecies(this);
this.conditions = new import_dex_conditions.DexConditions(this);
this.natures = new Data.DexNatures(this);
this.types = new Data.DexTypes(this);
this.stats = new Data.DexStats(this);
}
get data() {
return this.loadData();
}
get dexes() {
this.includeMods();
return dexes;
}
mod(mod) {
if (!dexes["base"].modsLoaded)
dexes["base"].includeMods();
return dexes[mod || "base"];
}
forGen(gen) {
if (!gen)
return this;
return this.mod(`gen${gen}`);
}
forFormat(format) {
if (!this.modsLoaded)
this.includeMods();
const mod = this.formats.get(format).mod;
return dexes[mod || BASE_MOD].includeData();
}
modData(dataType, id) {
if (this.isBase)
return this.data[dataType][id];
if (this.data[dataType][id] !== dexes[this.parentMod].data[dataType][id])
return this.data[dataType][id];
return this.data[dataType][id] = import_lib.Utils.deepClone(this.data[dataType][id]);
}
effectToString() {
return this.name;
}
/**
* Sanitizes a username or Pokemon nickname
*
* Returns the passed name, sanitized for safe use as a name in the PS
* protocol.
*
* Such a string must uphold these guarantees:
* - must not contain any ASCII whitespace character other than a space
* - must not start or end with a space character
* - must not contain any of: | , [ ]
* - must not be the empty string
* - must not contain Unicode RTL control characters
*
* If no such string can be found, returns the empty string. Calling
* functions are expected to check for that condition and deal with it
* accordingly.
*
* getName also enforces that there are not multiple consecutive space
* characters in the name, although this is not strictly necessary for
* safety.
*/
getName(name) {
if (typeof name !== "string" && typeof name !== "number")
return "";
name = ("" + name).replace(/[|\s[\],\u202e]+/g, " ").trim();
if (name.length > 18)
name = name.substr(0, 18).trim();
name = name.replace(
/[\u0300-\u036f\u0483-\u0489\u0610-\u0615\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06ED\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g,
""
);
name = name.replace(/[\u239b-\u23b9]/g, "");
return name;
}
/**
* Returns false if the target is immune; true otherwise.
* Also checks immunity to some statuses.
*/
getImmunity(source, target) {
const sourceType = typeof source !== "string" ? source.type : source;
const targetTyping = target.getTypes?.() || target.types || target;
if (Array.isArray(targetTyping)) {
for (const type of targetTyping) {
if (!this.getImmunity(sourceType, type))
return false;
}
return true;
}
const typeData = this.types.get(targetTyping);
if (typeData && typeData.damageTaken[sourceType] === 3)
return false;
return true;
}
getEffectiveness(source, target) {
const sourceType = typeof source !== "string" ? source.type : source;
const targetTyping = target.getTypes?.() || target.types || target;
let totalTypeMod = 0;
if (Array.isArray(targetTyping)) {
for (const type of targetTyping) {
totalTypeMod += this.getEffectiveness(sourceType, type);
}
return totalTypeMod;
}
const typeData = this.types.get(targetTyping);
if (!typeData)
return 0;
switch (typeData.damageTaken[sourceType]) {
case 1:
return 1;
case 2:
return -1;
default:
return 0;
}
}
getDescs(table, id, dataEntry) {
if (dataEntry.shortDesc) {
return {
desc: dataEntry.desc,
shortDesc: dataEntry.shortDesc
};
}
const entry = this.loadTextData()[table][id];
if (!entry)
return null;
const descs = {
desc: "",
shortDesc: ""
};
for (let i = this.gen; i < dexes["base"].gen; i++) {
const curDesc = entry[`gen${i}`]?.desc;
const curShortDesc = entry[`gen${i}`]?.shortDesc;
if (!descs.desc && curDesc) {
descs.desc = curDesc;
}
if (!descs.shortDesc && curShortDesc) {
descs.shortDesc = curShortDesc;
}
if (descs.desc && descs.shortDesc)
break;
}
if (!descs.shortDesc)
descs.shortDesc = entry.shortDesc || "";
if (!descs.desc)
descs.desc = entry.desc || descs.shortDesc;
return descs;
}
/**
* Ensure we're working on a copy of a move (and make a copy if we aren't)
*
* Remember: "ensure" - by default, it won't make a copy of a copy:
* moveCopy === Dex.getActiveMove(moveCopy)
*
* If you really want to, use:
* moveCopyCopy = Dex.getActiveMove(moveCopy.id)
*/
getActiveMove(move) {
if (move && typeof move.hit === "number")
return move;
move = this.moves.get(move);
const moveCopy = this.deepClone(move);
moveCopy.hit = 0;
return moveCopy;
}
getHiddenPower(ivs) {
const hpTypes = [
"Fighting",
"Flying",
"Poison",
"Ground",
"Rock",
"Bug",
"Ghost",
"Steel",
"Fire",
"Water",
"Grass",
"Electric",
"Psychic",
"Ice",
"Dragon",
"Dark"
];
const tr = this.trunc;
const stats = { hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31 };
if (this.gen <= 2) {
const atkDV = tr(ivs.atk / 2);
const defDV = tr(ivs.def / 2);
const speDV = tr(ivs.spe / 2);
const spcDV = tr(ivs.spa / 2);
return {
type: hpTypes[4 * (atkDV % 4) + defDV % 4],
power: tr(
(5 * ((spcDV >> 3) + 2 * (speDV >> 3) + 4 * (defDV >> 3) + 8 * (atkDV >> 3)) + spcDV % 4) / 2 + 31
)
};
} else {
let hpTypeX = 0;
let hpPowerX = 0;
let i = 1;
for (const s in stats) {
hpTypeX += i * (ivs[s] % 2);
hpPowerX += i * (tr(ivs[s] / 2) % 2);
i *= 2;
}
return {
type: hpTypes[tr(hpTypeX * 15 / 63)],
// After Gen 6, Hidden Power is always 60 base power
power: this.gen && this.gen < 6 ? tr(hpPowerX * 40 / 63) + 30 : 60
};
}
}
/**
* Truncate a number into an unsigned 32-bit integer, for
* compatibility with the cartridge games' math systems.
*/
trunc(num, bits = 0) {
if (bits)
return (num >>> 0) % 2 ** bits;
return num >>> 0;
}
dataSearch(target, searchIn, isInexact) {
if (!target)
return null;
searchIn = searchIn || ["Pokedex", "Moves", "Abilities", "Items", "Natures"];
const searchObjects = {
Pokedex: "species",
Moves: "moves",
Abilities: "abilities",
Items: "items",
Natures: "natures"
};
const searchTypes = {
Pokedex: "pokemon",
Moves: "move",
Abilities: "ability",
Items: "item",
Natures: "nature"
};
let searchResults = [];
for (const table of searchIn) {
const res = this[searchObjects[table]].get(target);
if (res.exists && res.gen <= this.gen) {
searchResults.push({
isInexact,
searchType: searchTypes[table],
name: res.name
});
}
}
if (searchResults.length)
return searchResults;
if (isInexact)
return null;
const cmpTarget = toID(target);
let maxLd = 3;
if (cmpTarget.length <= 1) {
return null;
} else if (cmpTarget.length <= 4) {
maxLd = 1;
} else if (cmpTarget.length <= 6) {
maxLd = 2;
}
searchResults = null;
for (const table of [...searchIn, "Aliases"]) {
const searchObj = this.data[table];
if (!searchObj)
continue;
for (const j in searchObj) {
const ld = import_lib.Utils.levenshtein(cmpTarget, j, maxLd);
if (ld <= maxLd) {
const word = searchObj[j].name || searchObj[j].species || j;
const results = this.dataSearch(word, searchIn, word);
if (results) {
searchResults = results;
maxLd = ld;
}
}
}
}
return searchResults;
}
loadDataFile(basePath, dataType) {
try {
const filePath = basePath + DATA_FILES[dataType];
const dataObject = require(filePath);
if (!dataObject || typeof dataObject !== "object") {
throw new TypeError(`${filePath}, if it exists, must export a non-null object`);
}
if (dataObject[dataType]?.constructor?.name !== "Object") {
throw new TypeError(`${filePath}, if it exists, must export an object whose '${dataType}' property is an Object`);
}
return dataObject[dataType];
} catch (e) {
}
return {};
}
loadTextFile(name, exportName) {
return require(`${DATA_DIR}/text/${name}`)[exportName];
}
includeMods() {
const all_mods = [
"fullpotential",
"gen1",
"gen1jpn",
"gen1stadium",
"gen2",
"gen2stadium2",
"gen3",
"gen4",
"gen4pt",
"gen5",
"gen5bw1",
"gen6",
"gen6xy",
"gen7",
"gen7letsgo",
"gen7sm",
"gen8",
"gen8bdsp",
"gen8dlc1",
"gen8joltemons",
"gen8linked",
"gennext",
"mixandmega",
"partnersincrime",
"pokebilities",
"potd",
"sharedpower",
"ssb",
"thecardgame",
"trademarked",
CobblemonCache.MOD_ID
];
if (!this.isBase)
throw new Error(`This must be called on the base Dex`);
if (this.modsLoaded)
return this;
for (let mod of all_mods) {
dexes[mod] = new ModdedDex(mod);
}
this.modsLoaded = true;
return this;
}
includeModData() {
for (const mod in this.dexes) {
dexes[mod].includeData();
}
return this;
}
includeData() {
this.loadData();
return this;
}
loadTextData() {
if (dexes["base"].textCache)
return dexes["base"].textCache;
dexes["base"].textCache = {
Pokedex: this.loadTextFile("pokedex", "PokedexText"),
Moves: this.loadTextFile("moves", "MovesText"),
Abilities: this.loadTextFile("abilities", "AbilitiesText"),
Items: this.loadTextFile("items", "ItemsText"),
Default: this.loadTextFile("default", "DefaultText")
};
return dexes["base"].textCache;
}
loadData() {
if (this.dataCache)
return this.dataCache;
dexes["base"].includeMods();
const dataCache = {};
const basePath = this.dataDir + "/";
const Scripts = this.loadDataFile(basePath, "Scripts");
this.parentMod = this.isBase ? "" : Scripts.inherit || "base";
let parentDex;
if (this.parentMod) {
parentDex = dexes[this.parentMod];
if (!parentDex || parentDex === this) {
throw new Error(
`Unable to load ${this.currentMod}. 'inherit' in scripts.ts should specify a parent mod from which to inherit data, or must be not specified.`
);
}
}
if (!parentDex) {
this.includeFormats();
}
for (const dataType of DATA_TYPES.concat("Aliases")) {
const BattleData = this.loadDataFile(basePath, dataType);
if (BattleData !== dataCache[dataType])
dataCache[dataType] = Object.assign(BattleData, dataCache[dataType]);
if (dataType === "Rulesets" && !parentDex) {
for (const format of this.formats.all()) {
BattleData[format.id] = { ...format, ruleTable: null };
}
}
}
if (parentDex) {
for (const dataType of DATA_TYPES) {
const parentTypedData = parentDex.data[dataType];
const childTypedData = dataCache[dataType] || (dataCache[dataType] = {});
for (const entryId in parentTypedData) {
if (childTypedData[entryId] === null) {
delete childTypedData[entryId];
} else if (!(entryId in childTypedData)) {
if (dataType === "Pokedex") {
childTypedData[entryId] = this.deepClone(parentTypedData[entryId]);
} else {
childTypedData[entryId] = parentTypedData[entryId];
}
} else if (childTypedData[entryId] && childTypedData[entryId].inherit) {
delete childTypedData[entryId].inherit;
for (const key in parentTypedData[entryId]) {
if (key in childTypedData[entryId])
continue;
childTypedData[entryId][key] = parentTypedData[entryId][key];
}
}
}
}
dataCache["Aliases"] = parentDex.data["Aliases"];
}
this.gen = dataCache.Scripts.gen;
if (!this.gen)
throw new Error(`Mod ${this.currentMod} needs a generation number in scripts.js`);
this.dataCache = dataCache;
if (Scripts.init)
Scripts.init.call(this);
return this.dataCache;
}
includeFormats() {
this.formats.load();
return this;
}
}
dexes["base"] = new ModdedDex();
dexes[BASE_MOD] = dexes["base"];
const Dex = dexes["base"];
var dex_default = Dex;
//# sourceMappingURL=dex.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/dex.ts"],
"sourcesContent": ["/**\r\n * Dex\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Handles getting data about pokemon, items, etc. Also contains some useful\r\n * helper functions for using dex data.\r\n *\r\n * By default, nothing is loaded until you call Dex.mod(mod) or\r\n * Dex.forFormat(format).\r\n *\r\n * You may choose to preload some things:\r\n * - Dex.includeMods() ~10ms\r\n * This will preload `Dex.dexes`, giving you a list of possible mods.\r\n * - Dex.includeFormats() ~30ms\r\n * As above, but will also preload `Dex.formats.all()`.\r\n * - Dex.includeData() ~500ms\r\n * As above, but will also preload all of Dex.data for Gen 8, so\r\n * functions like `Dex.species.get`, etc will be instantly usable.\r\n * - Dex.includeModData() ~1500ms\r\n * As above, but will also preload `Dex.dexes[...].data` for all mods.\r\n *\r\n * Note that preloading is never necessary. All the data will be\r\n * automatically preloaded when needed, preloading will just spend time\r\n * now so you don't need to spend time later.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport * as path from 'path';\r\n\r\nimport * as Data from './dex-data';\r\nimport {Condition, DexConditions} from './dex-conditions';\r\nimport {DataMove, DexMoves} from './dex-moves';\r\nimport {Item, DexItems} from './dex-items';\r\nimport {Ability, DexAbilities} from './dex-abilities';\r\nimport {Species, DexSpecies} from './dex-species';\r\nimport {Format, DexFormats} from './dex-formats';\r\nimport { Utils } from '../lib';\r\nimport * as CobblemonCache from './cobblemon-cache';\r\n\r\nconst BASE_MOD = 'gen9' as ID;\r\n// to account for Sucrase\r\nconst DATA_PATH = '../data';///pokemon-showdown/.data-dist';//__dirname.endsWith('.sim-dist') ? `../.data-dist` : `../data`;\r\nconst DATA_DIR = DATA_PATH;//path.resolve(__dirname, DATA_PATH);\r\nconst MODS_DIR = DATA_PATH + '/mods';//path.resolve(DATA_DIR, './mods');\r\n\r\nconst dexes: {[mod: string]: ModdedDex} = Object.create(null);\r\n\r\ntype DataType =\r\n\t'Abilities' | 'Rulesets' | 'FormatsData' | 'Items' | 'Learnsets' | 'Moves' |\r\n\t'Natures' | 'Pokedex' | 'Scripts' | 'Conditions' | 'TypeChart';\r\nconst DATA_TYPES: (DataType | 'Aliases')[] = [\r\n\t'Abilities', 'Rulesets', 'FormatsData', 'Items', 'Learnsets', 'Moves',\r\n\t'Natures', 'Pokedex', 'Scripts', 'Conditions', 'TypeChart',\r\n];\r\n\r\nconst DATA_FILES = {\r\n\tAbilities: 'abilities',\r\n\tAliases: 'aliases',\r\n\tRulesets: 'rulesets',\r\n\tFormatsData: 'formats-data',\r\n\tItems: 'items',\r\n\tLearnsets: 'learnsets',\r\n\tMoves: 'moves',\r\n\tNatures: 'natures',\r\n\tPokedex: 'pokedex',\r\n\tScripts: 'scripts',\r\n\tConditions: 'conditions',\r\n\tTypeChart: 'typechart',\r\n};\r\n\r\ninterface DexTable<T> {\r\n\t[key: string]: T;\r\n}\r\n\r\ninterface DexTableData {\r\n\tAbilities: DexTable<AbilityData>;\r\n\tAliases: {[id: string]: string};\r\n\tRulesets: DexTable<FormatData>;\r\n\tFormatsData: DexTable<import('./dex-species').ModdedSpeciesFormatsData>;\r\n\tItems: DexTable<ItemData>;\r\n\tLearnsets: DexTable<LearnsetData>;\r\n\tMoves: DexTable<MoveData>;\r\n\tNatures: DexTable<NatureData>;\r\n\tPokedex: DexTable<SpeciesData>;\r\n\tScripts: DexTable<AnyObject>;\r\n\tConditions: DexTable<EffectData>;\r\n\tTypeChart: DexTable<TypeData>;\r\n}\r\ninterface TextTableData {\r\n\tAbilities: DexTable<AbilityText>;\r\n\tItems: DexTable<ItemText>;\r\n\tMoves: DexTable<MoveText>;\r\n\tPokedex: DexTable<PokedexText>;\r\n\tDefault: DexTable<DefaultText>;\r\n}\r\n\r\nexport const toID = Data.toID;\r\n\r\nexport class ModdedDex {\r\n\treadonly Data = Data;\r\n\treadonly Condition = Condition;\r\n\treadonly Ability = Ability;\r\n\treadonly Item = Item;\r\n\treadonly Move = DataMove;\r\n\treadonly Species = Species;\r\n\treadonly Format = Format;\r\n\treadonly ModdedDex = ModdedDex;\r\n\r\n\treadonly name = \"[ModdedDex]\";\r\n\treadonly isBase: boolean;\r\n\treadonly currentMod: string;\r\n\treadonly dataDir: string;\r\n\r\n\treadonly toID = Data.toID;\r\n\r\n\tgen = 0;\r\n\tparentMod = '';\r\n\tmodsLoaded = false;\r\n\r\n\tdataCache: DexTableData | null;\r\n\ttextCache: TextTableData | null;\r\n\r\n\tdeepClone = Utils.deepClone;\r\n\r\n\treadonly formats: DexFormats;\r\n\treadonly abilities: DexAbilities;\r\n\treadonly items: DexItems;\r\n\treadonly moves: DexMoves;\r\n\treadonly species: DexSpecies;\r\n\treadonly conditions: DexConditions;\r\n\treadonly natures: Data.DexNatures;\r\n\treadonly types: Data.DexTypes;\r\n\treadonly stats: Data.DexStats;\r\n\r\n\tconstructor(mod = 'base') {\r\n\t\tthis.isBase = (mod === 'base');\r\n\t\tthis.currentMod = mod;\r\n\t\tthis.dataDir = (this.isBase ? DATA_DIR : MODS_DIR + '/' + this.currentMod);\r\n\r\n\t\tthis.dataCache = null;\r\n\t\tthis.textCache = null;\r\n\r\n\t\tthis.formats = new DexFormats(this);\r\n\t\tthis.abilities = new DexAbilities(this);\r\n\t\tthis.items = new DexItems(this);\r\n\t\tthis.moves = new DexMoves(this);\r\n\t\tthis.species = new DexSpecies(this);\r\n\t\ttLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BA,WAAsB;AACtB,4BAAuC;AACvC,uBAAiC;AACjC,uBAA6B;AAC7B,2BAAoC;AACpC,yBAAkC;AAClC,yBAAiC;AACjC,iBAAsB;AACtB,qBAAgC;AAtChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCA,MAAM,WAAW;AAEjB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,WAAW,YAAY;AAE7B,MAAM,QAAoC,uBAAO,OAAO,IAAI;AAK5D,MAAM,aAAuC;AAAA,EAC5C;AAAA,EAAa;AAAA,EAAY;AAAA,EAAe;AAAA,EAAS;AAAA,EAAa;AAAA,EAC9D;AAAA,EAAW;AAAA,EAAW;AAAA,EAAW;AAAA,EAAc;AAChD;AAEA,MAAM,aAAa;AAAA,EAClB,WAAW;AAAA,EACX,SAAS;AAAA,EACT,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO;AAAA,EACP,WAAW;AAAA,EACX,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,WAAW;AACZ;AA4BO,MAAM,OAAO,KAAK;AAElB,MAAM,UAAU;AAAA,EAoCtB,YAAY,MAAM,QAAQ;AAnC1B,SAAS,OAAO;AAChB,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,OAAO;AAChB,SAAS,OAAO;AAChB,SAAS,UAAU;AACnB,SAAS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M;AAClD,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,cAAc,MAAiC;AAC9C,QAAI,QAAQ,OAAQ,KAAoB,QAAQ;AAAU,aAAO;AACjE,WAAO,KAAK,MAAM,IAAI,IAAI;AAC1B,UAAM,WAAuB,KAAK,UAAU,IAAI;AAChD,aAAS,MAAM;AACf,WAAO;AAAA,EACR;AAAA,EAEA,eAAe,KAAgB;AAC9B,UAAM,UAAU;AAAA,MACf;AAAA,MAAY;AAAA,MAAU;AAAA,MAAU;AAAA,MAAU;AAAA,MAAQ;AAAA,MAAO;AAAA,MAAS;AAAA,MAClE;AAAA,MAAQ;AAAA,MAAS;AAAA,MAAS;AAAA,MAAY;AAAA,MAAW;AAAA,MAAO;AAAA,MAAU;AAAA,IACnE;AACA,UAAM,KAAK,KAAK;AAChB,UAAM,QAAQ,EAAC,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,GAAE;AAClE,QAAI,KAAK,OAAO,GAAG;AAElB,YAAM,QAAQ,GAAG,IAAI,MAAM,CAAC;AAC5B,YAAM,QAAQ,GAAG,IAAI,MAAM,CAAC;AAC5B,YAAM,QAAQ,GAAG,IAAI,MAAM,CAAC;AAC5B,YAAM,QAAQ,GAAG,IAAI,MAAM,CAAC;AAC5B,aAAO;AAAA,QACN,MAAM,QAAQ,KAAK,QAAQ,KAAM,QAAQ,CAAE;AAAA,QAC3C,OAAO;AAAA,WACL,MAAM,SAAS,KAAM,KAAK,SAAS,KAAO,KAAK,SAAS,KAAO,KAAK,SAAS,MAAQ,QAAQ,KAAM,IAAI;AAAA,QACzG;AAAA,MACD;AAAA,IACD,OAAO;AAEN,UAAI,UAAU;AACd,UAAI,WAALine truncated
"names": []
}
@@ -0,0 +1,40 @@
"use strict";
var import__ = require("..");
var import_random_player_ai = require("../tools/random-player-ai");
/**
* Battle Stream Example
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Example of how to create AIs battling against each other.
* Run this using `node build && node .sim-dist/examples/battle-stream-example`.
*
* @license MIT
* @author Guangcong Luo <guangcongluo@gmail.com>
*/
const streams = (0, import__.getPlayerStreams)(new import__.BattleStream());
const spec = {
formatid: "gen7customgame"
};
const p1spec = {
name: "Bot 1",
team: import__.Teams.pack(import__.Teams.generate("gen7randombattle"))
};
const p2spec = {
name: "Bot 2",
team: import__.Teams.pack(import__.Teams.generate("gen7randombattle"))
};
const p1 = new import_random_player_ai.RandomPlayerAI(streams.p1);
const p2 = new import_random_player_ai.RandomPlayerAI(streams.p2);
console.log("p1 is " + p1.constructor.name);
console.log("p2 is " + p2.constructor.name);
void p1.start();
void p2.start();
void (async () => {
for await (const chunk of streams.omniscient) {
console.log(chunk);
}
})();
void streams.omniscient.write(`>start ${JSON.stringify(spec)}
>player p1 ${JSON.stringify(p1spec)}
>player p2 ${JSON.stringify(p2spec)}`);
//# sourceMappingURL=battle-stream-example.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../../sim/examples/battle-stream-example.ts"],
"sourcesContent": ["/**\r\n * Battle Stream Example\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Example of how to create AIs battling against each other.\r\n * Run this using `node build && node .sim-dist/examples/battle-stream-example`.\r\n *\r\n * @license MIT\r\n * @author Guangcong Luo <guangcongluo@gmail.com>\r\n */\r\n\r\nimport {BattleStream, getPlayerStreams, Teams} from '..';\r\nimport {RandomPlayerAI} from '../tools/random-player-ai';\r\n\r\n/*********************************************************************\r\n * Run AI\r\n *********************************************************************/\r\n\r\nconst streams = getPlayerStreams(new BattleStream());\r\n\r\nconst spec = {\r\n\tformatid: \"gen7customgame\",\r\n};\r\nconst p1spec = {\r\n\tname: \"Bot 1\",\r\n\tteam: Teams.pack(Teams.generate('gen7randombattle')),\r\n};\r\nconst p2spec = {\r\n\tname: \"Bot 2\",\r\n\tteam: Teams.pack(Teams.generate('gen7randombattle')),\r\n};\r\n\r\nconst p1 = new RandomPlayerAI(streams.p1);\r\nconst p2 = new RandomPlayerAI(streams.p2);\r\n\r\nconsole.log(\"p1 is \" + p1.constructor.name);\r\nconsole.log(\"p2 is \" + p2.constructor.name);\r\n\r\nvoid p1.start();\r\nvoid p2.start();\r\n\r\nvoid (async () => {\r\n\tfor await (const chunk of streams.omniscient) {\r\n\t\tconsole.log(chunk);\r\n\t}\r\n})();\r\n\r\nvoid streams.omniscient.write(`>start ${JSON.stringify(spec)}\r\n>player p1 ${JSON.stringify(p1spec)}\r\n>player p2 ${JSON.stringify(p2spec)}`);\r\n"],
"mappings": ";AAWA,eAAoD;AACpD,8BAA6B;AAZ7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,MAAM,cAAU,2BAAiB,IAAI,sBAAa,CAAC;AAEnD,MAAM,OAAO;AAAA,EACZ,UAAU;AACX;AACA,MAAM,SAAS;AAAA,EACd,MAAM;AAAA,EACN,MAAM,eAAM,KAAK,eAAM,SAAS,kBAAkB,CAAC;AACpD;AACA,MAAM,SAAS;AAAA,EACd,MAAM;AAAA,EACN,MAAM,eAAM,KAAK,eAAM,SAAS,kBAAkB,CAAC;AACpD;AAEA,MAAM,KAAK,IAAI,uCAAe,QAAQ,EAAE;AACxC,MAAM,KAAK,IAAI,uCAAe,QAAQ,EAAE;AAExC,QAAQ,IAAI,WAAW,GAAG,YAAY,IAAI;AAC1C,QAAQ,IAAI,WAAW,GAAG,YAAY,IAAI;AAE1C,KAAK,GAAG,MAAM;AACd,KAAK,GAAG,MAAM;AAEd,MAAM,YAAY;AACjB,mBAAiB,SAAS,QAAQ,YAAY;AAC7C,YAAQ,IAAI,KAAK;AAAA,EAClB;AACD,GAAG;AAEH,KAAK,QAAQ,WAAW,MAAM,UAAU,KAAK,UAAU,IAAI;AAAA,aAC9C,KAAK,UAAU,MAAM;AAAA,aACrB,KAAK,UAAU,MAAM,GAAG;",
"names": []
}
+241
View File
@@ -0,0 +1,241 @@
"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 field_exports = {};
__export(field_exports, {
Field: () => Field
});
module.exports = __toCommonJS(field_exports);
var import_state = require("./state");
var import_dex = require("./dex");
/**
* Simulator Field
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT
*/
class Field {
constructor(battle) {
this.battle = battle;
const fieldScripts = this.battle.format.field || this.battle.dex.data.Scripts.field;
if (fieldScripts)
Object.assign(this, fieldScripts);
this.id = "";
this.weather = "";
this.weatherState = { id: "" };
this.terrain = "";
this.terrainState = { id: "" };
this.pseudoWeather = {};
}
toJSON() {
return import_state.State.serializeField(this);
}
setWeather(status, source = null, sourceEffect = null) {
status = this.battle.dex.conditions.get(status);
if (!sourceEffect && this.battle.effect)
sourceEffect = this.battle.effect;
if (!source && this.battle.event && this.battle.event.target)
source = this.battle.event.target;
if (source === "debug")
source = this.battle.sides[0].active[0];
if (this.weather === status.id) {
if (sourceEffect && sourceEffect.effectType === "Ability") {
if (this.battle.gen > 5 || this.weatherState.duration === 0) {
return false;
}
} else if (this.battle.gen > 2 || status.id === "sandstorm") {
return false;
}
}
if (source) {
const result = this.battle.runEvent("SetWeather", source, source, status);
if (!result) {
if (result === false) {
if (sourceEffect?.weather) {
this.battle.add("-fail", source, sourceEffect, "[from] " + this.weather);
} else if (sourceEffect && sourceEffect.effectType === "Ability") {
this.battle.add("-ability", source, sourceEffect, "[from] " + this.weather, "[fail]");
}
}
return null;
}
}
const prevWeather = this.weather;
const prevWeatherState = this.weatherState;
this.weather = status.id;
this.weatherState = { id: status.id };
if (source) {
this.weatherState.source = source;
this.weatherState.sourceSlot = source.getSlot();
}
if (status.duration) {
this.weatherState.duration = status.duration;
}
if (status.durationCallback) {
if (!source)
throw new Error(`setting weather without a source`);
this.weatherState.duration = status.durationCallback.call(this.battle, source, source, sourceEffect);
}
if (!this.battle.singleEvent("FieldStart", status, this.weatherState, this, source, sourceEffect)) {
this.weather = prevWeather;
this.weatherState = prevWeatherState;
return false;
}
this.battle.eachEvent("WeatherChange", sourceEffect);
return true;
}
clearWeather() {
if (!this.weather)
return false;
const prevWeather = this.getWeather();
this.battle.singleEvent("FieldEnd", prevWeather, this.weatherState, this);
this.weather = "";
this.weatherState = { id: "" };
this.battle.eachEvent("WeatherChange");
return true;
}
effectiveWeather() {
if (this.suppressingWeather())
return "";
return this.weather;
}
suppressingWeather() {
for (const side of this.battle.sides) {
for (const pokemon of side.active) {
if (pokemon && !pokemon.fainted && !pokemon.ignoringAbility() && pokemon.getAbility().suppressWeather) {
return true;
}
}
}
return false;
}
isWeather(weather) {
const ourWeather = this.effectiveWeather();
if (!Array.isArray(weather)) {
return ourWeather === (0, import_dex.toID)(weather);
}
return weather.map(import_dex.toID).includes(ourWeather);
}
getWeather() {
return this.battle.dex.conditions.getByID(this.weather);
}
setTerrain(status, source = null, sourceEffect = null) {
status = this.battle.dex.conditions.get(status);
if (!sourceEffect && this.battle.effect)
sourceEffect = this.battle.effect;
if (!source && this.battle.event && this.battle.event.target)
source = this.battle.event.target;
if (source === "debug")
source = this.battle.sides[0].active[0];
if (!source)
throw new Error(`setting terrain without a source`);
if (this.terrain === status.id)
return false;
const prevTerrain = this.terrain;
const prevTerrainState = this.terrainState;
this.terrain = status.id;
this.terrainState = {
id: status.id,
source,
sourceSlot: source.getSlot(),
duration: status.duration
};
if (status.durationCallback) {
this.terrainState.duration = status.durationCallback.call(this.battle, source, source, sourceEffect);
}
if (!this.battle.singleEvent("FieldStart", status, this.terrainState, this, source, sourceEffect)) {
this.terrain = prevTerrain;
this.terrainState = prevTerrainState;
return false;
}
this.battle.eachEvent("TerrainChange", sourceEffect);
return true;
}
clearTerrain() {
if (!this.terrain)
return false;
const prevTerrain = this.getTerrain();
this.battle.singleEvent("FieldEnd", prevTerrain, this.terrainState, this);
this.terrain = "";
this.terrainState = { id: "" };
this.battle.eachEvent("TerrainChange");
return true;
}
effectiveTerrain(target) {
if (this.battle.event && !target)
target = this.battle.event.target;
return this.battle.runEvent("TryTerrain", target) ? this.terrain : "";
}
isTerrain(terrain, target) {
const ourTerrain = this.effectiveTerrain(target);
if (!Array.isArray(terrain)) {
return ourTerrain === (0, import_dex.toID)(terrain);
}
return terrain.map(import_dex.toID).includes(ourTerrain);
}
getTerrain() {
return this.battle.dex.conditions.getByID(this.terrain);
}
addPseudoWeather(status, source = null, sourceEffect = null) {
if (!source && this.battle.event && this.battle.event.target)
source = this.battle.event.target;
if (source === "debug")
source = this.battle.sides[0].active[0];
status = this.battle.dex.conditions.get(status);
let state = this.pseudoWeather[status.id];
if (state) {
if (!status.onFieldRestart)
return false;
return this.battle.singleEvent("FieldRestart", status, state, this, source, sourceEffect);
}
state = this.pseudoWeather[status.id] = {
id: status.id,
source,
sourceSlot: source?.getSlot(),
duration: status.duration
};
if (status.durationCallback) {
if (!source)
throw new Error(`setting fieldcond without a source`);
state.duration = status.durationCallback.call(this.battle, source, source, sourceEffect);
}
if (!this.battle.singleEvent("FieldStart", status, state, this, source, sourceEffect)) {
delete this.pseudoWeather[status.id];
return false;
}
this.battle.runEvent("PseudoWeatherChange", source, source, status);
return true;
}
getPseudoWeather(status) {
status = this.battle.dex.conditions.get(status);
return this.pseudoWeather[status.id] ? status : null;
}
removePseudoWeather(status) {
status = this.battle.dex.conditions.get(status);
const state = this.pseudoWeather[status.id];
if (!state)
return false;
this.battle.singleEvent("FieldEnd", status, state, this);
delete this.pseudoWeather[status.id];
return true;
}
destroy() {
this.battle = null;
}
}
//# sourceMappingURL=field.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/field.ts"],
"sourcesContent": ["/**\r\n * Simulator Field\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {State} from './state';\r\nimport {EffectState} from './pokemon';\r\nimport {toID} from './dex';\r\n\r\nexport class Field {\r\n\treadonly battle: Battle;\r\n\treadonly id: ID;\r\n\r\n\tweather: ID;\r\n\tweatherState: EffectState;\r\n\tterrain: ID;\r\n\tterrainState: EffectState;\r\n\tpseudoWeather: {[id: string]: EffectState};\r\n\r\n\tconstructor(battle: Battle) {\r\n\t\tthis.battle = battle;\r\n\t\tconst fieldScripts = this.battle.format.field || this.battle.dex.data.Scripts.field;\r\n\t\tif (fieldScripts) Object.assign(this, fieldScripts);\r\n\t\tthis.id = '';\r\n\r\n\t\tthis.weather = '';\r\n\t\tthis.weatherState = {id: ''};\r\n\t\tthis.terrain = '';\r\n\t\tthis.terrainState = {id: ''};\r\n\t\tthis.pseudoWeather = {};\r\n\t}\r\n\r\n\ttoJSON(): AnyObject {\r\n\t\treturn State.serializeField(this);\r\n\t}\r\n\r\n\tsetWeather(status: string | Condition, source: Pokemon | 'debug' | null = null, sourceEffect: Effect | null = null) {\r\n\t\tstatus = this.battle.dex.conditions.get(status);\r\n\t\tif (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect;\r\n\t\tif (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target;\r\n\t\tif (source === 'debug') source = this.battle.sides[0].active[0];\r\n\r\n\t\tif (this.weather === status.id) {\r\n\t\t\tif (sourceEffect && sourceEffect.effectType === 'Ability') {\r\n\t\t\t\tif (this.battle.gen > 5 || this.weatherState.duration === 0) {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t} else if (this.battle.gen > 2 || status.id === 'sandstorm') {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (source) {\r\n\t\t\tconst result = this.battle.runEvent('SetWeather', source, source, status);\r\n\t\t\tif (!result) {\r\n\t\t\t\tif (result === false) {\r\n\t\t\t\t\tif ((sourceEffect as Move)?.weather) {\r\n\t\t\t\t\t\tthis.battle.add('-fail', source, sourceEffect, '[from] ' + this.weather);\r\n\t\t\t\t\t} else if (sourceEffect && sourceEffect.effectType === 'Ability') {\r\n\t\t\t\t\t\tthis.battle.add('-ability', source, sourceEffect, '[from] ' + this.weather, '[fail]');\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}\r\n\t\tconst prevWeather = this.weather;\r\n\t\tconst prevWeatherState = this.weatherState;\r\n\t\tthis.weather = status.id;\r\n\t\tthis.weatherState = {id: status.id};\r\n\t\tif (source) {\r\n\t\t\tthis.weatherState.source = source;\r\n\t\t\tthis.weatherState.sourceSlot = source.getSlot();\r\n\t\t}\r\n\t\tif (status.duration) {\r\n\t\t\tthis.weatherState.duration = status.duration;\r\n\t\t}\r\n\t\tif (status.durationCallback) {\r\n\t\t\tif (!source) throw new Error(`setting weather without a source`);\r\n\t\t\tthis.weatherState.duration = status.durationCallback.call(this.battle, source, source, sourceEffect);\r\n\t\t}\r\n\t\tif (!this.battle.singleEvent('FieldStart', status, this.weatherState, this, source, sourceEffect)) {\r\n\t\t\tthis.weather = prevWeather;\r\n\t\t\tthis.weatherState = prevWeatherState;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tthis.battle.eachEvent('WeatherChange', sourceEffect);\r\n\t\treturn true;\r\n\t}\r\n\r\n\tclearWeather() {\r\n\t\tif (!this.weather) return false;\r\n\t\tconst prevWeather = this.getWeather();\r\n\t\tthis.battle.singleEvent('FieldEnd', prevWeather, this.weatherState, this);\r\n\t\tthis.weather = '';\r\n\t\tthis.weatherState = {id: ''};\r\n\t\tthis.battle.eachEvent('WeatherChange');\r\n\t\treturn true;\r\n\t}\r\n\r\n\teffectiveWeather() {\r\n\t\tif (this.suppressingWeather()) return '';\r\n\t\treturn this.weather;\r\n\t}\r\n\r\n\tsuppressingWeather() {\r\n\t\tfor (const side of this.battle.sides) {\r\n\t\t\tfor (const pokemon of side.active) {\r\n\t\t\t\tif (pokemon && !pokemon.fainted && !pokemon.ignoringAbility() && pokemon.getAbility().suppressWeather) {\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tisWeather(weather: string | string[]) {\r\n\t\tconst ourWeather = this.effectiveWeather();\r\n\t\tif (!Array.isArray(weather)) {\r\n\t\t\treturn ourWeather === toID(weather);\r\n\t\t}\r\n\t\treturn weather.map(toID).includes(ourWeather);\r\n\t}\r\n\r\n\tgetWeather() {\r\n\t\treturn this.battle.dex.conditions.getByID(this.weather);\r\n\t}\r\n\r\n\tsetTerrain(status: string | Effect, source: Pokemon | 'debug' | null = null, sourceEffect: Effect | null = null) {\r\n\t\tstatus = this.battle.dex.conditions.get(status);\r\n\t\tif (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect;\r\n\t\tif (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target;\r\n\t\tif (source === 'debug') source = this.battle.sides[0].active[0];\r\n\t\tif (!source) throw new Error(`setting terrain without a source`);\r\n\r\n\t\tif (this.terrain === status.id) return false;\r\n\t\tconst prevTerrain = this.terrain;\r\n\t\tconstLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAoB;AAEpB,iBAAmB;AATnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,MAAM,MAAM;AAAA,EAUlB,YAAY,QAAgB;AAC3B,SAAK,SAAS;AACd,UAAM,eAAe,KAAK,OAAO,OAAO,SAAS,KAAK,OAAO,IAAI,KAAK,QAAQ;AAC9E,QAAI;AAAc,aAAO,OAAO,MAAM,YAAY;AA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AQ,QAAQ;AAAA,MAC5B,UAAU,OAAO;AAAA,IAClB;AACA,QAAI,OAAO,kBAAkB;AAC5B,UAAI,CAAC;AAAQ,cAAM,IAAI,MAAM,oCAAoC;AACjE,YAAM,WAAW,OAAO,iBAAiB,KAAK,KAAK,QAAQ,QAAQ,QAAQ,YAAY;AAAA,IACxF;AACA,QAAI,CAAC,KAAK,OAAO,YAAY,cAAc,QAAQ,OAAO,MAAM,QAAQ,YAAY,GAAG;AACtF,aAAO,KAAK,cAAc,OAAO,EAAE;AACnC,aAAO;AAAA,IACR;AACA,SAAK,OAAO,SAAS,uBAAuB,QAAQ,QAAQ,MAAM;AAClE,WAAO;AAAA,EACR;AAAA,EAEA,iBAAiB,QAAyB;AACzC,aAAS,KAAK,OAAO,IAAI,WAAW,IAAI,MAAM;AAC9C,WAAO,KAAK,cAAc,OAAO,EAAE,IAAI,SAAS;AAAA,EACjD;AAAA,EAEA,oBAAoB,QAAyB;AAC5C,aAAS,KAAK,OAAO,IAAI,WAAW,IAAI,MAAM;AAC9C,UAAM,QAAQ,KAAK,cAAc,OAAO,EAAE;Line truncated
"names": []
}
+52
View File
@@ -0,0 +1,52 @@
"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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var sim_exports = {};
__export(sim_exports, {
Battle: () => import_battle.Battle,
BattleStream: () => import_battle_stream.BattleStream,
Dex: () => import_dex.Dex,
PRNG: () => import_prng.PRNG,
Pokemon: () => import_pokemon.Pokemon,
Side: () => import_side.Side,
TeamValidator: () => import_team_validator.TeamValidator,
Teams: () => import_teams.Teams,
getPlayerStreams: () => import_battle_stream.getPlayerStreams,
toID: () => import_dex.toID
});
module.exports = __toCommonJS(sim_exports);
var import_battle = require("./battle");
var import_battle_stream = require("./battle-stream");
var import_pokemon = require("./pokemon");
var import_prng = require("./prng");
var import_side = require("./side");
var import_dex = require("./dex");
var import_teams = require("./teams");
var import_team_validator = require("./team-validator");
__reExport(sim_exports, require("../lib"), module.exports);
/**
* Simulator
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Here's where all the simulator APIs get exported for general use.
* `require('pokemon-showdown')` imports from here.
*
* @license MIT
*/
//# sourceMappingURL=index.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/index.ts"],
"sourcesContent": ["/**\r\n * Simulator\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Here's where all the simulator APIs get exported for general use.\r\n * `require('pokemon-showdown')` imports from here.\r\n *\r\n * @license MIT\r\n */\r\n\r\n// battle simulation\r\n\r\nexport {Battle} from './battle';\r\nexport {BattleStream, getPlayerStreams} from './battle-stream';\r\nexport {Pokemon} from './pokemon';\r\nexport {PRNG} from './prng';\r\nexport {Side} from './side';\r\n\r\n// dex API\r\n\r\nexport {Dex, toID} from './dex';\r\n\r\n// teams API\r\n\r\nexport {Teams} from './teams';\r\nexport {TeamValidator} from './team-validator';\r\n\r\n// misc libraries\r\n\r\nexport * from '../lib';\r\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,oBAAqB;AACrB,2BAA6C;AAC7C,qBAAsB;AACtB,kBAAmB;AACnB,kBAAmB;AAInB,iBAAwB;AAIxB,mBAAoB;AACpB,4BAA4B;AAI5B,wBAAc,mBA7Bd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
"names": []
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/pokemon.ts"],
"sourcesContent": ["/**\r\n * Simulator Pokemon\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * @license MIT license\r\n */\r\n\r\nimport {State} from './state';\r\nimport {toID} from './dex';\r\n\r\n/** A Pokemon's move slot. */\r\ninterface MoveSlot {\r\n\tid: ID;\r\n\tmove: string;\r\n\tpp: number;\r\n\tmaxpp: number;\r\n\ttarget?: string;\r\n\tdisabled: boolean | string;\r\n\tdisabledSource?: string;\r\n\tused: boolean;\r\n\tvirtual?: boolean;\r\n}\r\n\r\ninterface Attacker {\r\n\tsource: Pokemon;\r\n\tdamage: number;\r\n\tthisTurn: boolean;\r\n\tmove?: ID;\r\n\tslot: PokemonSlot;\r\n\tdamageValue?: (number | boolean | undefined);\r\n}\r\n\r\nexport interface EffectState {\r\n\t// TODO: set this to be an actual number after converting data/ to .ts\r\n\tduration?: number | any;\r\n\t[k: string]: any;\r\n}\r\n\r\n// Berries which restore PP/HP and thus inflict external staleness when given to an opponent as\r\n// there are very few non-malicious competitive reasons to do so\r\nexport const RESTORATIVE_BERRIES = new Set([\r\n\t'leppaberry', 'aguavberry', 'enigmaberry', 'figyberry', 'iapapaberry', 'magoberry', 'sitrusberry', 'wikiberry', 'oranberry',\r\n] as ID[]);\r\n\r\nexport class Pokemon {\r\n\treadonly side: Side;\r\n\treadonly battle: Battle;\r\n\r\n\treadonly set: PokemonSet;\r\n\treadonly name: string;\r\n\treadonly fullname: string;\r\n\treadonly level: number;\r\n\treadonly gender: GenderName;\r\n\treadonly happiness: number;\r\n\treadonly pokeball: string;\r\n\treadonly dynamaxLevel: number;\r\n\treadonly gigantamax: boolean;\r\n\r\n\t/** Transform keeps the original pre-transformed Hidden Power in Gen 2-4. */\r\n\treadonly baseHpType: string;\r\n\treadonly baseHpPower: number;\r\n\r\n\treadonly baseMoveSlots: MoveSlot[];\r\n\tmoveSlots: MoveSlot[];\r\n\r\n\thpType: string;\r\n\thpPower: number;\r\n\r\n\t/**\r\n\t * Index of `pokemon.side.pokemon` and `pokemon.side.active`, which are\r\n\t * guaranteed to be the same for active pokemon. Note that this isn't\r\n\t * its field position in multi battles - use `getSlot()` for that.\r\n\t */\r\n\tposition: number;\r\n\tdetails: string;\r\n\tuuid: string;\r\n\r\n\tbaseSpecies: Species;\r\n\tspecies: Species;\r\n\tspeciesState: EffectState;\r\n\r\n\tstatus: ID;\r\n\tstatusState: EffectState;\r\n\tvolatiles: {[id: string]: EffectState};\r\n\tshowCure?: boolean;\r\n\r\n\t/**\r\n\t * These are the basic stats that appear on the in-game stats screen:\r\n\t * calculated purely from the species base stats, level, IVs, EVs,\r\n\t * and Nature, before modifications from item, ability, etc.\r\n\t *\r\n\t * Forme changes affect these, but Transform doesn't.\r\n\t */\r\n\tbaseStoredStats: StatsTable;\r\n\t/**\r\n\t * These are pre-modification stored stats in-battle. At switch-in,\r\n\t * they're identical to `baseStoredStats`, but can be temporarily changed\r\n\t * until switch-out by effects such as Power Trick and Transform.\r\n\t *\r\n\t * Stat multipliers from abilities, items, and volatiles, such as\r\n\t * Solar Power, Choice Band, or Swords Dance, are not stored in\r\n\t * `storedStats`, but applied on top and accessed by `pokemon.getStat`.\r\n\t *\r\n\t * (Except in Gen 1, where stat multipliers are stored, leading\r\n\t * to several famous glitches.)\r\n\t */\r\n\tstoredStats: StatsExceptHPTable;\r\n\tboosts: BoostsTable;\r\n\r\n\tbaseAbility: ID;\r\n\tability: ID;\r\n\tabilityState: EffectState;\r\n\r\n\titem: ID;\r\n\titemState: EffectState;\r\n\tlastItem: ID;\r\n\tusedItemThisTurn: boolean;\r\n\tateBerry: boolean;\r\n\r\n\ttrapped: boolean | \"hidden\";\r\n\tmaybeTrapped: boolean;\r\n\tmaybeDisabled: boolean;\r\n\r\n\tillusion: Pokemon | null;\r\n\ttransformed: boolean;\r\n\r\n\tmaxhp: number;\r\n\t/** This is the max HP before Dynamaxing; it's updated for Power Construct etc */\r\n\tbaseMaxhp: number;\r\n\thp: number;\r\n\tfainted: boolean;\r\n\tfaintQueued: boolean;\r\n\tsubFainted: boolean | null;\r\n\r\n\ttypes: string[];\r\n\taddedType: string;\r\n\tknownType: boolean;\r\n\t/** Keeps track of what type the client sees for this Pokemon. */\r\n\tapparentType: string;\r\n\r\n\t/**\r\n\t * If the switch is called by an effect with a special switch\r\n\t * message, like U-turn or Baton Pass, this will be the ID of\r\n\t * the calling effect.\r\n\t */\r\n\tswitchFlag: ID | boolean;\r\n\tforceSwitchFlag: boolean;\r\n\tskipBeforeSwitchOutEventFlag: boolean;\r\n\tdraggedIn: number | null;\r\n\tnewlySwitched: boolean;\r\n\tbeingCalledBack: boolean;\r\n\r\n\tlastMove: ActiveMove | null;\r\n\t// Gen 2 only\r\n\tlastMoveEncore?: ActiveMove | null;\r\n\tlastMoveUsed: ActiveMove | null;\r\n\tlastMoveTargetLoc?: number;\r\n\tmoveThisTurn: string | boolean;\r\n\tstatsRaisedThisTurn: boolean;\r\n\tstatsLoweredThisTurn: boolean;\r\n\t/**\r\n\t * The result of the last move used on the previous turn by this\r\n\t * Pokemon. Stomping Tantrum checks this property for a value of false\r\n\t * when determine whether to double its power, but it has fLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAoB;AACpB,iBAAmB;AARnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCO,MAAM,sBAAsB,oBAAI,IAAI;AAAA,EAC1C;AAAA,EAAc;AAAA,EAAc;AAAA,EAAe;AAAA,EAAa;AAAA,EAAe;AAAA,EAAa;AAAA,EAAe;AAAA,EAAa;AACjH,CAAS;AAEF,MAAM,QAAQ;AAAA,E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,IAAI,UAAU,OAAO;AACnC,SAAK,UAAU,OAAO;AAEtB,SAAK,aAAa,KAAK;AACvB,SAAK,cAAc,KAAK;AAGxB,SAAK,kBAAkB;AACvB,SAAK,cAAc,EAAC,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,EAAC;AAC1D,SAAK,SAAS,EAAC,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,GAAG,UAAU,GAAG,SAAS,EAAC;AAE9E,SAAK,kBAAc,iBAAK,IAAI,OAAO;AACnC,SAAK,UAAU,KAAK;AACpB,SAAK,eAAe,EAAC,IAAI,KAAK,QAAO;AAErC,SAAK,WAAO,iBAAK,IAAI,IAAI;AACzB,SAAK,YAAY,EAAC,IAAI,KAAK,KAAI;AAC/B,SAAK,WAAW;AAChB,SAAK,mBAAmB;AACxB,SAAK,WAAW;AAEhB,SAAK,UAAU;AACf,SAAK,eAAe;AACpB,SAAK,gBAAgB;AAErB,SAAK,WAAW;AAChB,SAAK,cAAc;AAEnB,SAAK,UAAU;AACf,SAAK,cAAc;AACnB,SAAKLine truncated
"names": []
}
+184
View File
@@ -0,0 +1,184 @@
"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 prng_exports = {};
__export(prng_exports, {
PRNG: () => PRNG
});
module.exports = __toCommonJS(prng_exports);
/**
* PRNG
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This simulates the on-cartridge PRNG used in the real games.
*
* In addition to potentially allowing us to read replays from in-game,
* this also makes it possible to record an "input log" (a seed +
* initial teams + move/switch decisions) and "replay" a simulation to
* get the same result.
*
* @license MIT license
*/
class PRNG {
/** Creates a new source of randomness for the given seed. */
constructor(seed = null) {
if (!seed)
seed = PRNG.generateSeed();
this.initialSeed = seed.slice();
this.seed = seed.slice();
}
/**
* Getter to the initial seed.
*
* This should be considered a hack and is only here for backwards compatibility.
*/
get startingSeed() {
return this.initialSeed;
}
/**
* Creates a clone of the current PRNG.
*
* The new PRNG will have its initial seed set to the seed of the current instance.
*/
clone() {
return new PRNG(this.seed);
}
/**
* Retrieves the next random number in the sequence.
* This function has three different results, depending on arguments:
* - random() returns a real number in [0, 1), just like Math.random()
* - random(n) returns an integer in [0, n)
* - random(m, n) returns an integer in [m, n)
* m and n are converted to integers via Math.floor. If the result is NaN, they are ignored.
*/
next(from, to) {
this.seed = this.nextFrame(this.seed);
let result = (this.seed[0] << 16 >>> 0) + this.seed[1];
if (from)
from = Math.floor(from);
if (to)
to = Math.floor(to);
if (from === void 0) {
result = result / 4294967296;
} else if (!to) {
result = Math.floor(result * from / 4294967296);
} else {
result = Math.floor(result * (to - from) / 4294967296) + from;
}
return result;
}
/**
* Flip a coin (two-sided die), returning true or false.
*
* This function returns true with probability `P`, where `P = numerator
* / denominator`. This function returns false with probability `1 - P`.
*
* The numerator must be a non-negative integer (`>= 0`).
*
* The denominator must be a positive integer (`> 0`).
*/
randomChance(numerator, denominator) {
return this.next(denominator) < numerator;
}
/**
* Return a random item from the given array.
*
* This function chooses items in the array with equal probability.
*
* If there are duplicate items in the array, each duplicate is
* considered separately. For example, sample(['x', 'x', 'y']) returns
* 'x' 67% of the time and 'y' 33% of the time.
*
* The array must contain at least one item.
*
* The array must not be sparse.
*/
sample(items) {
if (items.length === 0) {
throw new RangeError(`Cannot sample an empty array`);
}
const index = this.next(items.length);
const item = items[index];
if (item === void 0 && !Object.prototype.hasOwnProperty.call(items, index)) {
throw new RangeError(`Cannot sample a sparse array`);
}
return item;
}
/**
* A Fisher-Yates shuffle. This is how the game resolves speed ties.
*
* At least according to V4 in
* https://github.com/smogon/pokemon-showdown/issues/1157#issuecomment-214454873
*/
shuffle(items, start = 0, end = items.length) {
while (start < end - 1) {
const nextIndex = this.next(start, end);
if (start !== nextIndex) {
[items[start], items[nextIndex]] = [items[nextIndex], items[start]];
}
start++;
}
}
/**
* Calculates `a * b + c` (with 64-bit 2's complement integers)
*
* If you've done long multiplication, this is the same thing.
*/
multiplyAdd(a, b, c) {
const out = [0, 0, 0, 0];
let carry = 0;
for (let outIndex = 3; outIndex >= 0; outIndex--) {
for (let bIndex = outIndex; bIndex < 4; bIndex++) {
const aIndex = 3 - (bIndex - outIndex);
carry += a[aIndex] * b[bIndex];
}
carry += c[outIndex];
out[outIndex] = carry & 65535;
carry >>>= 16;
}
return out;
}
/**
* The RNG is a Linear Congruential Generator (LCG) in the form: `x_{n + 1} = (a x_n + c) % m`
*
* Where: `x_0` is the seed, `x_n` is the random number after n iterations,
*
* ````
* a = 0x5D588B656C078965
* c = 0x00269EC3
* m = 2^64
* ````
*/
nextFrame(seed, framesToAdvance = 1) {
const a = [23896, 35685, 27655, 35173];
const c = [0, 0, 38, 40643];
for (let i = 0; i < framesToAdvance; i++) {
seed = this.multiplyAdd(seed, a, c);
}
return seed;
}
static generateSeed() {
return [
Math.floor(Math.random() * 65536),
Math.floor(Math.random() * 65536),
Math.floor(Math.random() * 65536),
Math.floor(Math.random() * 65536)
];
}
}
//# sourceMappingURL=prng.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/prng.ts"],
"sourcesContent": ["/**\r\n * PRNG\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * This simulates the on-cartridge PRNG used in the real games.\r\n *\r\n * In addition to potentially allowing us to read replays from in-game,\r\n * this also makes it possible to record an \"input log\" (a seed +\r\n * initial teams + move/switch decisions) and \"replay\" a simulation to\r\n * get the same result.\r\n *\r\n * @license MIT license\r\n */\r\n\r\n/** 64-bit big-endian [high -> low] int */\r\nexport type PRNGSeed = [number, number, number, number];\r\n\r\n/**\r\n * A PRNG intended to emulate the on-cartridge PRNG for Gen 5 with a 64-bit\r\n * initial seed.\r\n */\r\nexport class PRNG {\r\n\treadonly initialSeed: PRNGSeed;\r\n\tseed: PRNGSeed;\r\n\t/** Creates a new source of randomness for the given seed. */\r\n\tconstructor(seed: PRNGSeed | null = null) {\r\n\t\tif (!seed) seed = PRNG.generateSeed();\r\n\t\tthis.initialSeed = seed.slice() as PRNGSeed; // make a copy\r\n\t\tthis.seed = seed.slice() as PRNGSeed;\r\n\t}\r\n\r\n\t/**\r\n\t * Getter to the initial seed.\r\n\t *\r\n\t * This should be considered a hack and is only here for backwards compatibility.\r\n\t */\r\n\tget startingSeed(): PRNGSeed {\r\n\t\treturn this.initialSeed;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a clone of the current PRNG.\r\n\t *\r\n\t * The new PRNG will have its initial seed set to the seed of the current instance.\r\n\t */\r\n\tclone(): PRNG {\r\n\t\treturn new PRNG(this.seed);\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieves the next random number in the sequence.\r\n\t * This function has three different results, depending on arguments:\r\n\t * - random() returns a real number in [0, 1), just like Math.random()\r\n\t * - random(n) returns an integer in [0, n)\r\n\t * - random(m, n) returns an integer in [m, n)\r\n\t * m and n are converted to integers via Math.floor. If the result is NaN, they are ignored.\r\n\t */\r\n\tnext(from?: number, to?: number): number {\r\n\t\tthis.seed = this.nextFrame(this.seed); // Advance the RNG\r\n\t\tlet result = (this.seed[0] << 16 >>> 0) + this.seed[1]; // Use the upper 32 bits\r\n\t\tif (from) from = Math.floor(from);\r\n\t\tif (to) to = Math.floor(to);\r\n\t\tif (from === undefined) {\r\n\t\t\tresult = result / 0x100000000;\r\n\t\t} else if (!to) {\r\n\t\t\tresult = Math.floor(result * from / 0x100000000);\r\n\t\t} else {\r\n\t\t\tresult = Math.floor(result * (to - from) / 0x100000000) + from;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * Flip a coin (two-sided die), returning true or false.\r\n\t *\r\n\t * This function returns true with probability `P`, where `P = numerator\r\n\t * / denominator`. This function returns false with probability `1 - P`.\r\n\t *\r\n\t * The numerator must be a non-negative integer (`>= 0`).\r\n\t *\r\n\t * The denominator must be a positive integer (`> 0`).\r\n\t */\r\n\trandomChance(numerator: number, denominator: number): boolean {\r\n\t\treturn this.next(denominator) < numerator;\r\n\t}\r\n\r\n\t/**\r\n\t * Return a random item from the given array.\r\n\t *\r\n\t * This function chooses items in the array with equal probability.\r\n\t *\r\n\t * If there are duplicate items in the array, each duplicate is\r\n\t * considered separately. For example, sample(['x', 'x', 'y']) returns\r\n\t * 'x' 67% of the time and 'y' 33% of the time.\r\n\t *\r\n\t * The array must contain at least one item.\r\n\t *\r\n\t * The array must not be sparse.\r\n\t */\r\n\tsample<T>(items: readonly T[]): T {\r\n\t\tif (items.length === 0) {\r\n\t\t\tthrow new RangeError(`Cannot sample an empty array`);\r\n\t\t}\r\n\t\tconst index = this.next(items.length);\r\n\t\tconst item = items[index];\r\n\t\tif (item === undefined && !Object.prototype.hasOwnProperty.call(items, index)) {\r\n\t\t\tthrow new RangeError(`Cannot sample a sparse array`);\r\n\t\t}\r\n\t\treturn item;\r\n\t}\r\n\r\n\t/**\r\n\t * A Fisher-Yates shuffle. This is how the game resolves speed ties.\r\n\t *\r\n\t * At least according to V4 in\r\n\t * https://github.com/smogon/pokemon-showdown/issues/1157#issuecomment-214454873\r\n\t */\r\n\tshuffle<T>(items: T[], start = 0, end: number = items.length) {\r\n\t\twhile (start < end - 1) {\r\n\t\t\tconst nextIndex = this.next(start, end);\r\n\t\t\tif (start !== nextIndex) {\r\n\t\t\t\t[items[start], items[nextIndex]] = [items[nextIndex], items[start]];\r\n\t\t\t}\r\n\t\t\tstart++;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Calculates `a * b + c` (with 64-bit 2's complement integers)\r\n\t *\r\n\t * If you've done long multiplication, this is the same thing.\r\n\t */\r\n\tmultiplyAdd(a: PRNGSeed, b: PRNGSeed, c: PRNGSeed) {\r\n\t\tconst out: PRNGSeed = [0, 0, 0, 0];\r\n\t\tlet carry = 0;\r\n\r\n\t\tfor (let outIndex = 3; outIndex >= 0; outIndex--) {\r\n\t\t\tfor (let bIndex = outIndex; bIndex < 4; bIndex++) {\r\n\t\t\t\tconst aIndex = 3 - (bIndex - outIndex);\r\n\r\n\t\t\t\tcarry += a[aIndex] * b[bIndex];\r\n\t\t\t}\r\n\t\t\tcarry += c[outIndex];\r\n\r\n\t\t\tout[outILine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,MAAM,KAAK;AAAA;AAAA,EAIjB,YAAY,OAAwB,MAAM;AACzC,QAAI,CAAC;AAAM,aAAO,KAAK,aAAa;AACpC,SAAK,cAAc,KAAK,MAAM;AAC9B,SAAK,OAAO,KAAK,MAAM;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,eAAyB;AAC5B,WAAO,KAAK;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAc;AACb,WAAO,IAAI,KAAK,KAAK,IAAI;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,KAAK,MAAe,IAAqB;AACxC,SAAK,OAAO,KAAK,UAAU,KAAK,IAAI;AACpC,QAAI,UAAU,KAAK,KAAK,CAAC,KAAK,OAAO,KAAK,KAAK,KAAK,CAAC;AACrD,QAAI;AAAM,aAAO,KAAK,MAAM,IAAI;AAChC,QAAI;AAAI,WAAK,KAAK,MAAM,EAAE;A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GAAG,YAAY,GAAG,YAAY;AACjD,eAAS,SAAS,UAAU,SAAS,GAAG,UAAU;AACjD,cAAM,SAAS,KAAK,SAAS;AAE7B,iBAAS,EAAE,MAAM,IAAI,EAAE,MAAM;AAAA,MAC9B;AACA,eAAS,EAAE,QAAQ;AAEnB,UAAI,QAAQ,IAAI,QAAQ;AACxB,iBAAW;AAAA,IACZ;AAEA,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,UAAU,MAAgB,kBAAkB,GAAa;AACxD,UAAM,IAAc,CAAC,OAAQ,OAAQ,OAAQ,KAAM;AACnD,UAAM,IAAc,CAAC,GAAG,GAAG,IAAM,KAAM;AAEvC,aAAS,IAAI,GAAG,IAAI,iBAAiB,KAAK;AACzC,aAAO,KAAK,YAAY,MAAM,GAAG,CAAC;AAAA,IACnC;AAEA,WAAO;AAAA,EACR;AAAA,EAEA,OAAO,eAAe;AACrB,WAAO;AAAA,MACN,KAAK,MAAM,KAAK,OAAO,IAAI,KAAO;AAAA,MAClC,KAAK,MAAM,KAAK,OAAO,IAAI,KAAO;AAAA,MAClC,KAAK,MAAM,KAAK,OAAO,IAAI,KAAO;AAAA,MAClC,KAAK,MAAM,KAAK,OAAO,IAAI,KAAO;AAAA,IACnC;AAAA,EACD;AACD;",
"names": []
}
+997
View File
@@ -0,0 +1,997 @@
"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 side_exports = {};
__export(side_exports, {
Side: () => Side
});
module.exports = __toCommonJS(side_exports);
var import_lib = require("../lib");
var import_pokemon = require("./pokemon");
var import_state = require("./state");
var import_dex = require("./dex");
/**
* Simulator Side
* Pokemon Showdown - http://pokemonshowdown.com/
*
* There's a lot of ambiguity between the terms "player", "side", "team",
* and "half-field", which I'll try to explain here:
*
* These terms usually all mean the same thing. The exceptions are:
*
* - Multi-battle: there are 2 half-fields, 2 teams, 4 sides
*
* - Free-for-all: there are 2 half-fields, 4 teams, 4 sides
*
* "Half-field" is usually abbreviated to "half".
*
* Function naming will be very careful about which term to use. Pay attention
* if it's relevant to your code.
*
* @license MIT
*/
class Side {
constructor(name, battle, sideNum, team) {
this.foe = null;
// set in battle.start()
/** Only exists in multi battle, for the allied side */
this.allySide = null;
/** only used by Gen 1 Counter */
this.lastSelectedMove = "";
const sideScripts = battle.dex.data.Scripts.side;
if (sideScripts)
Object.assign(this, sideScripts);
this.battle = battle;
this.id = ["p1", "p2", "p3", "p4"][sideNum];
this.n = sideNum;
this.name = name;
this.avatar = "";
this.team = team;
this.pokemon = [];
for (let i = 0; i < this.team.length && i < 24; i++) {
this.pokemon.push(new import_pokemon.Pokemon(this.team[i], this));
this.pokemon[i].position = i;
}
switch (this.battle.gameType) {
case "doubles":
this.active = [null, null];
break;
case "triples":
case "rotation":
this.active = [null, null, null];
break;
default:
this.active = [null];
}
this.pokemonLeft = this.pokemon.length;
this.faintedLastTurn = null;
this.faintedThisTurn = null;
this.totalFainted = 0;
this.zMoveUsed = false;
this.dynamaxUsed = this.battle.gen !== 8;
this.sideConditions = {};
this.slotConditions = [];
for (let i = 0; i < this.active.length; i++)
this.slotConditions[i] = {};
this.activeRequest = null;
this.choice = {
cantUndo: false,
error: ``,
actions: [],
forcedSwitchesLeft: 0,
forcedPassesLeft: 0,
switchIns: /* @__PURE__ */ new Set(),
zMove: false,
mega: false,
ultra: false,
dynamax: false,
terastallize: false
};
this.lastMove = null;
}
toJSON() {
return import_state.State.serializeSide(this);
}
get requestState() {
if (!this.activeRequest || this.activeRequest.wait)
return "";
if (this.activeRequest.teamPreview)
return "teampreview";
if (this.activeRequest.forceSwitch)
return "switch";
return "move";
}
canDynamaxNow() {
if (this.battle.gen !== 8)
return false;
if (this.battle.gameType === "multi" && this.battle.turn % 2 !== [1, 1, 0, 0][this.n])
return false;
return !this.dynamaxUsed;
}
getChoice() {
if (this.choice.actions.length > 1 && this.choice.actions.every((action) => action.choice === "team")) {
return `team ` + this.choice.actions.map((action) => action.pokemon.position + 1).join(", ");
}
return this.choice.actions.map((action) => {
switch (action.choice) {
case "move":
let details = ``;
if (action.targetLoc && this.active.length > 1)
details += ` ${action.targetLoc > 0 ? "+" : ""}${action.targetLoc}`;
if (action.mega)
details += action.pokemon.item === "ultranecroziumz" ? ` ultra` : ` mega`;
if (action.zmove)
details += ` zmove`;
if (action.maxMove)
details += ` dynamax`;
if (action.terastallize)
details += ` terastallize`;
return `move ${action.moveid}${details}`;
case "switch":
case "instaswitch":
case "revivalblessing":
return `switch ${action.target.position + 1}`;
case "team":
return `team ${action.pokemon.position + 1}`;
default:
return action.choice;
}
}).join(", ");
}
toString() {
return `${this.id}: ${this.name}`;
}
getRequestData(forAlly) {
const data = {
name: this.name,
id: this.id,
pokemon: []
};
for (const pokemon of this.pokemon) {
data.pokemon.push(pokemon.getSwitchRequestData(forAlly));
}
return data;
}
randomFoe() {
const actives = this.foes();
if (!actives.length)
return null;
return this.battle.sample(actives);
}
/** Intended as a way to iterate through all foe side conditions - do not use for anything else. */
foeSidesWithConditions() {
if (this.battle.gameType === "freeforall")
return this.battle.sides.filter((side) => side !== this);
return [this.foe];
}
foePokemonLeft() {
if (this.battle.gameType === "freeforall") {
return this.battle.sides.filter((side) => side !== this).map((side) => side.pokemonLeft).reduce((a, b) => a + b);
}
if (this.foe.allySide)
return this.foe.pokemonLeft + this.foe.allySide.pokemonLeft;
return this.foe.pokemonLeft;
}
allies(all) {
let allies = this.activeTeam().filter((ally) => ally);
if (!all)
allies = allies.filter((ally) => !!ally.hp);
return allies;
}
foes(all) {
if (this.battle.gameType === "freeforall") {
return this.battle.sides.map((side) => side.active[0]).filter((pokemon) => pokemon && pokemon.side !== this && (all || !!pokemon.hp));
}
return this.foe.allies(all);
}
activeTeam() {
if (this.battle.gameType !== "multi")
return this.active;
return this.battle.sides[this.n % 2].active.concat(this.battle.sides[this.n % 2 + 2].active);
}
hasAlly(pokemon) {
return pokemon.side === this || pokemon.side === this.allySide;
}
addSideCondition(status, source = null, sourceEffect = null) {
if (!source && this.battle.event && this.battle.event.target)
source = this.battle.event.target;
if (source === "debug")
source = this.active[0];
if (!source)
throw new Error(`setting sidecond without a source`);
if (!source.getSlot)
source = source.active[0];
status = this.battle.dex.conditions.get(status);
if (this.sideConditions[status.id]) {
if (!status.onSideRestart)
return false;
return this.battle.singleEvent("SideRestart", status, this.sideConditions[status.id], this, source, sourceEffect);
}
this.sideConditions[status.id] = {
id: status.id,
target: this,
source,
sourceSlot: source.getSlot(),
duration: status.duration
};
if (status.durationCallback) {
this.sideConditions[status.id].duration = status.durationCallback.call(this.battle, this.active[0], source, sourceEffect);
}
if (!this.battle.singleEvent("SideStart", status, this.sideConditions[status.id], this, source, sourceEffect)) {
delete this.sideConditions[status.id];
return false;
}
this.battle.runEvent("SideConditionStart", source, source, status);
return true;
}
getSideCondition(status) {
status = this.battle.dex.conditions.get(status);
if (!this.sideConditions[status.id])
return null;
return status;
}
getSideConditionData(status) {
status = this.battle.dex.conditions.get(status);
return this.sideConditions[status.id] || null;
}
removeSideCondition(status) {
status = this.battle.dex.conditions.get(status);
if (!this.sideConditions[status.id])
return false;
this.battle.singleEvent("SideEnd", status, this.sideConditions[status.id], this);
delete this.sideConditions[status.id];
return true;
}
addSlotCondition(target, status, source = null, sourceEffect = null) {
if (!source && this.battle.event && this.battle.event.target)
source = this.battle.event.target;
if (source === "debug")
source = this.active[0];
if (target instanceof import_pokemon.Pokemon)
target = target.position;
if (!source)
throw new Error(`setting sidecond without a source`);
status = this.battle.dex.conditions.get(status);
if (this.slotConditions[target][status.id]) {
if (!status.onRestart)
return false;
return this.battle.singleEvent("Restart", status, this.slotConditions[target][status.id], this, source, sourceEffect);
}
const conditionState = this.slotConditions[target][status.id] = {
id: status.id,
target: this,
source,
sourceSlot: source.getSlot(),
duration: status.duration
};
if (status.durationCallback) {
conditionState.duration = status.durationCallback.call(this.battle, this.active[0], source, sourceEffect);
}
if (!this.battle.singleEvent("Start", status, conditionState, this.active[target], source, sourceEffect)) {
delete this.slotConditions[target][status.id];
return false;
}
return true;
}
getSlotCondition(target, status) {
if (target instanceof import_pokemon.Pokemon)
target = target.position;
status = this.battle.dex.conditions.get(status);
if (!this.slotConditions[target][status.id])
return null;
return status;
}
removeSlotCondition(target, status) {
if (target instanceof import_pokemon.Pokemon)
target = target.position;
status = this.battle.dex.conditions.get(status);
if (!this.slotConditions[target][status.id])
return false;
this.battle.singleEvent("End", status, this.slotConditions[target][status.id], this.active[target]);
delete this.slotConditions[target][status.id];
return true;
}
// eslint-disable-next-line @typescript-eslint/ban-types
send(...parts) {
const sideUpdate = "|" + parts.map((part) => {
if (typeof part !== "function")
return part;
return part(this);
}).join("|");
this.battle.send("sideupdate", `${this.id}
${sideUpdate}`);
}
emitRequest(update) {
this.battle.send("sideupdate", `${this.id}
|request|${JSON.stringify(update)}`);
this.activeRequest = update;
}
emitChoiceError(message, unavailable) {
this.choice.error = message;
const type = `[${unavailable ? "Unavailable" : "Invalid"} choice]`;
this.battle.send("sideupdate", `${this.id}
|error|${type} ${message}`);
if (this.battle.strictChoices)
throw new Error(`${type} ${message}`);
return false;
}
isChoiceDone() {
if (!this.requestState)
return true;
if (this.choice.forcedSwitchesLeft)
return false;
if (this.requestState === "teampreview") {
return this.choice.actions.length >= this.pickedTeamSize();
}
this.getChoiceIndex();
return this.choice.actions.length >= this.active.length;
}
chooseMove(moveText, targetLoc = 0, event = "") {
if (this.requestState !== "move") {
return this.emitChoiceError(`Can't move: You need a ${this.requestState} response`);
}
const index = this.getChoiceIndex();
if (index >= this.active.length) {
return this.emitChoiceError(`Can't move: You sent more choices than unfainted Pok\xE9mon.`);
}
const autoChoose = !moveText;
const pokemon = this.active[index];
const request = pokemon.getMoveRequestData();
let moveid = "";
let targetType = "";
if (autoChoose)
moveText = 1;
if (typeof moveText === "number" || moveText && /^[0-9]+$/.test(moveText)) {
const moveIndex = Number(moveText) - 1;
if (moveIndex < 0 || moveIndex >= request.moves.length || !request.moves[moveIndex]) {
return this.emitChoiceError(`Can't move: Your ${pokemon.name} doesn't have a move ${moveIndex + 1}`);
}
moveid = request.moves[moveIndex].id;
targetType = request.moves[moveIndex].target;
} else {
moveid = (0, import_dex.toID)(moveText);
if (moveid.startsWith("hiddenpower")) {
moveid = "hiddenpower";
}
for (const move2 of request.moves) {
if (move2.id !== moveid)
continue;
targetType = move2.target || "normal";
break;
}
if (!targetType && ["", "dynamax"].includes(event) && request.maxMoves) {
for (const [i, moveRequest] of request.maxMoves.maxMoves.entries()) {
if (moveid === moveRequest.move) {
moveid = request.moves[i].id;
targetType = moveRequest.target;
event = "dynamax";
break;
}
}
}
if (!targetType && ["", "zmove"].includes(event) && request.canZMove) {
for (const [i, moveRequest] of request.canZMove.entries()) {
if (!moveRequest)
continue;
if (moveid === (0, import_dex.toID)(moveRequest.move)) {
moveid = request.moves[i].id;
targetType = moveRequest.target;
event = "zmove";
break;
}
}
}
if (!targetType) {
return this.emitChoiceError(`Can't move: Your ${pokemon.name} doesn't have a move matching ${moveid}`);
}
}
const moves = pokemon.getMoves();
if (autoChoose) {
for (const [i, move2] of request.moves.entries()) {
if (move2.disabled)
continue;
if (i < moves.length && move2.id === moves[i].id && moves[i].disabled)
continue;
moveid = move2.id;
targetType = move2.target;
break;
}
}
const move = this.battle.dex.moves.get(moveid);
const zMove = event === "zmove" ? this.battle.actions.getZMove(move, pokemon) : void 0;
if (event === "zmove" && !zMove) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't use ${move.name} as a Z-move`);
}
if (zMove && this.choice.zMove) {
return this.emitChoiceError(`Can't move: You can't Z-move more than once per battle`);
}
if (zMove)
targetType = this.battle.dex.moves.get(zMove).target;
const maxMove = event === "dynamax" || pokemon.volatiles["dynamax"] ? this.battle.actions.getMaxMove(move, pokemon) : void 0;
if (event === "dynamax" && !maxMove) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't use ${move.name} as a Max Move`);
}
if (maxMove)
targetType = this.battle.dex.moves.get(maxMove).target;
if (autoChoose) {
targetLoc = 0;
} else if (this.battle.actions.targetTypeChoices(targetType)) {
if (!targetLoc && this.active.length >= 2) {
return this.emitChoiceError(`Can't move: ${move.name} needs a target`);
}
if (!this.battle.validTargetLoc(targetLoc, pokemon, targetType)) {
return this.emitChoiceError(`Can't move: Invalid target for ${move.name}`);
}
} else {
if (targetLoc) {
return this.emitChoiceError(`Can't move: You can't choose a target for ${move.name}`);
}
}
const lockedMove = pokemon.getLockedMove();
if (lockedMove) {
let lockedMoveTargetLoc = pokemon.lastMoveTargetLoc || 0;
const lockedMoveID = (0, import_dex.toID)(lockedMove);
if (pokemon.volatiles[lockedMoveID] && pokemon.volatiles[lockedMoveID].targetLoc) {
lockedMoveTargetLoc = pokemon.volatiles[lockedMoveID].targetLoc;
}
this.choice.actions.push({
choice: "move",
pokemon,
targetLoc: lockedMoveTargetLoc,
moveid: lockedMoveID
});
return true;
} else if (!moves.length && !zMove) {
if (this.battle.gen <= 4)
this.send("-activate", pokemon, "move: Struggle");
moveid = "struggle";
} else if (maxMove) {
if (pokemon.maxMoveDisabled(move)) {
return this.emitChoiceError(`Can't move: ${pokemon.name}'s ${maxMove.name} is disabled`);
}
} else if (!zMove) {
let isEnabled = false;
let disabledSource = "";
for (const m of moves) {
if (m.id !== moveid)
continue;
if (!m.disabled) {
isEnabled = true;
break;
} else if (m.disabledSource) {
disabledSource = m.disabledSource;
}
}
if (!isEnabled) {
if (autoChoose)
throw new Error(`autoChoose chose a disabled move`);
const includeRequest = this.updateRequestForPokemon(pokemon, (req) => {
let updated = false;
for (const m of req.moves) {
if (m.id === moveid) {
if (!m.disabled) {
m.disabled = true;
updated = true;
}
if (m.disabledSource !== disabledSource) {
m.disabledSource = disabledSource;
updated = true;
}
break;
}
}
return updated;
});
const status = this.emitChoiceError(`Can't move: ${pokemon.name}'s ${move.name} is disabled`, includeRequest);
if (includeRequest)
this.emitRequest(this.activeRequest);
return status;
}
}
const mega = event === "mega";
if (mega && !pokemon.canMegaEvo) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't mega evolve`);
}
if (mega && this.choice.mega) {
return this.emitChoiceError(`Can't move: You can only mega-evolve once per battle`);
}
const ultra = event === "ultra";
if (ultra && !pokemon.canUltraBurst) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't ultra burst`);
}
if (ultra && this.choice.ultra) {
return this.emitChoiceError(`Can't move: You can only ultra burst once per battle`);
}
let dynamax = event === "dynamax";
const canDynamax = this.activeRequest?.active[this.active.indexOf(pokemon)].canDynamax;
if (dynamax && (this.choice.dynamax || !canDynamax)) {
if (pokemon.volatiles["dynamax"]) {
dynamax = false;
} else {
if (this.battle.gen !== 8) {
return this.emitChoiceError(`Can't move: Dynamaxing doesn't outside of Gen 8.`);
} else if (pokemon.side.canDynamaxNow()) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't Dynamax now.`);
} else if (pokemon.side.allySide?.canDynamaxNow()) {
return this.emitChoiceError(`Can't move: It's your partner's turn to Dynamax.`);
}
return this.emitChoiceError(`Can't move: You can only Dynamax once per battle.`);
}
}
const terastallize = event === "terastallize";
if (terastallize && !pokemon.canTerastallize) {
return this.emitChoiceError(`Can't move: ${pokemon.name} can't Terastallize.`);
}
if (terastallize && this.choice.terastallize) {
return this.emitChoiceError(`Can't move: You can only Terastallize once per battle.`);
}
if (terastallize && this.battle.gen !== 9) {
return this.emitChoiceError(`Can't move: You can only Terastallize in Gen 9.`);
}
this.choice.actions.push({
choice: "move",
pokemon,
targetLoc,
moveid,
mega: mega || ultra,
zmove: zMove,
maxMove: maxMove ? maxMove.id : void 0,
terastallize: terastallize ? pokemon.teraType : void 0
});
if (pokemon.maybeDisabled) {
this.choice.cantUndo = this.choice.cantUndo || pokemon.isLastActive();
}
if (mega)
this.choice.mega = true;
if (ultra)
this.choice.ultra = true;
if (zMove)
this.choice.zMove = true;
if (dynamax)
this.choice.dynamax = true;
if (terastallize)
this.choice.terastallize = true;
return true;
}
updateRequestForPokemon(pokemon, update) {
if (!this.activeRequest?.active) {
throw new Error(`Can't update a request without active Pokemon`);
}
const req = this.activeRequest.active[pokemon.position];
if (!req)
throw new Error(`Pokemon not found in request's active field`);
return update(req);
}
chooseSwitch(slotText) {
if (this.requestState !== "move" && this.requestState !== "switch") {
return this.emitChoiceError(`Can't switch: You need a ${this.requestState} response`);
}
const index = this.getChoiceIndex();
if (index >= this.active.length) {
if (this.requestState === "switch") {
return this.emitChoiceError(`Can't switch: You sent more switches than Pok\xE9mon that need to switch`);
}
return this.emitChoiceError(`Can't switch: You sent more choices than unfainted Pok\xE9mon`);
}
const pokemon = this.active[index];
let slot;
if (!slotText) {
if (this.requestState !== "switch") {
return this.emitChoiceError(`Can't switch: You need to select a Pok\xE9mon to switch in`);
}
if (this.slotConditions[pokemon.position]["revivalblessing"]) {
slot = 0;
while (!this.pokemon[slot].fainted)
slot++;
} else {
if (!this.choice.forcedSwitchesLeft)
return this.choosePass();
slot = this.active.length;
while (this.choice.switchIns.has(slot) || this.pokemon[slot].fainted)
slot++;
}
} else {
slot = parseInt(slotText) - 1;
}
if (isNaN(slot) || slot < 0 || slotText.length > 2) {
slot = -1;
for (const [i, mon] of this.pokemon.entries()) {
if (slotText.toLowerCase() === mon.name.toLowerCase() || (0, import_dex.toID)(slotText) === mon.species.id || slotText === mon.uuid) {
slot = i;
break;
}
}
if (slot < 0) {
return this.emitChoiceError(`Can't switch: You do not have a Pok\xE9mon named "${slotText}" to switch to`);
}
}
if (slot >= this.pokemon.length) {
return this.emitChoiceError(`Can't switch: You do not have a Pok\xE9mon in slot ${slot + 1} to switch to`);
} else if (slot < this.active.length && !this.slotConditions[pokemon.position]["revivalblessing"]) {
return this.emitChoiceError(`Can't switch: You can't switch to an active Pok\xE9mon`);
} else if (this.choice.switchIns.has(slot)) {
return this.emitChoiceError(`Can't switch: The Pok\xE9mon in slot ${slot + 1} can only switch in once`);
}
const targetPokemon = this.pokemon[slot];
if (this.slotConditions[pokemon.position]["revivalblessing"]) {
if (!targetPokemon.fainted) {
return this.emitChoiceError(`Can't switch: You have to pass to a fainted Pok\xE9mon`);
}
this.choice.forcedSwitchesLeft = this.battle.clampIntRange(this.choice.forcedSwitchesLeft - 1, 0);
pokemon.switchFlag = false;
this.choice.actions.push({
choice: "revivalblessing",
pokemon,
target: targetPokemon
});
return true;
}
if (targetPokemon.fainted) {
return this.emitChoiceError(`Can't switch: You can't switch to a fainted Pok\xE9mon`);
}
if (this.requestState === "move") {
if (pokemon.trapped) {
const includeRequest = this.updateRequestForPokemon(pokemon, (req) => {
let updated = false;
if (req.maybeTrapped) {
delete req.maybeTrapped;
updated = true;
}
if (!req.trapped) {
req.trapped = true;
updated = true;
}
return updated;
});
const status = this.emitChoiceError(`Can't switch: The active Pok\xE9mon is trapped`, includeRequest);
if (includeRequest)
this.emitRequest(this.activeRequest);
return status;
} else if (pokemon.maybeTrapped) {
this.choice.cantUndo = this.choice.cantUndo || pokemon.isLastActive();
}
} else if (this.requestState === "switch") {
if (!this.choice.forcedSwitchesLeft) {
throw new Error(`Player somehow switched too many Pokemon`);
}
this.choice.forcedSwitchesLeft--;
}
this.choice.switchIns.add(slot);
this.choice.actions.push({
choice: this.requestState === "switch" ? "instaswitch" : "switch",
pokemon,
target: targetPokemon
});
return true;
}
/**
* The number of pokemon you must choose in Team Preview.
*
* Note that PS doesn't support choosing fewer than this number of pokemon.
* In the games, it is sometimes possible to bring fewer than this, but
* since that's nearly always a mistake, we haven't gotten around to
* supporting it.
*/
pickedTeamSize() {
return Math.min(this.pokemon.length, this.battle.ruleTable.pickedTeamSize || Infinity);
}
chooseTeam(data = "") {
if (this.requestState !== "teampreview") {
return this.emitChoiceError(`Can't choose for Team Preview: You're not in a Team Preview phase`);
}
const ruleTable = this.battle.ruleTable;
let positions = data.split(data.includes(",") ? "," : "").map((datum) => parseInt(datum) - 1);
const pickedTeamSize = this.pickedTeamSize();
positions.splice(pickedTeamSize);
if (positions.length === 0) {
for (let i = 0; i < pickedTeamSize; i++)
positions.push(i);
} else if (positions.length < pickedTeamSize) {
for (let i = 0; i < pickedTeamSize; i++) {
if (!positions.includes(i))
positions.push(i);
if (positions.length >= pickedTeamSize)
break;
}
}
for (const [index, pos] of positions.entries()) {
if (isNaN(pos) || pos < 0 || pos >= this.pokemon.length) {
return this.emitChoiceError(`Can't choose for Team Preview: You do not have a Pok\xE9mon in slot ${pos + 1}`);
}
if (positions.indexOf(pos) !== index) {
return this.emitChoiceError(`Can't choose for Team Preview: The Pok\xE9mon in slot ${pos + 1} can only switch in once`);
}
}
if (ruleTable.maxTotalLevel) {
let totalLevel = 0;
for (const pos of positions)
totalLevel += this.pokemon[pos].level;
if (totalLevel > ruleTable.maxTotalLevel) {
if (!data) {
positions = [...this.pokemon.keys()].sort((a, b) => this.pokemon[a].level - this.pokemon[b].level).slice(0, pickedTeamSize);
} else {
return this.emitChoiceError(`Your selected team has a total level of ${totalLevel}, but it can't be above ${ruleTable.maxTotalLevel}; please select a valid team of ${pickedTeamSize} Pok\xE9mon`);
}
}
}
if (ruleTable.valueRules.has("forceselect")) {
const species = this.battle.dex.species.get(ruleTable.valueRules.get("forceselect"));
if (!data) {
positions = [...this.pokemon.keys()].filter((pos) => this.pokemon[pos].species.name === species.name).concat([...this.pokemon.keys()].filter((pos) => this.pokemon[pos].species.name !== species.name)).slice(0, pickedTeamSize);
} else {
let hasSelection = false;
for (const pos of positions) {
if (this.pokemon[pos].species.name === species.name) {
hasSelection = true;
break;
}
}
if (!hasSelection) {
return this.emitChoiceError(`You must bring ${species.name} to the battle.`);
}
}
}
for (const [index, pos] of positions.entries()) {
this.choice.switchIns.add(pos);
this.choice.actions.push({
choice: "team",
index,
pokemon: this.pokemon[pos],
priority: -index
});
}
return true;
}
chooseShift() {
const index = this.getChoiceIndex();
if (index >= this.active.length) {
return this.emitChoiceError(`Can't shift: You do not have a Pok\xE9mon in slot ${index + 1}`);
} else if (this.requestState !== "move") {
return this.emitChoiceError(`Can't shift: You can only shift during a move phase`);
} else if (this.battle.gameType !== "triples") {
return this.emitChoiceError(`Can't shift: You can only shift to the center in triples`);
} else if (index === 1) {
return this.emitChoiceError(`Can't shift: You can only shift from the edge to the center`);
}
const pokemon = this.active[index];
this.choice.actions.push({
choice: "shift",
pokemon
});
return true;
}
clearChoice() {
let forcedSwitches = 0;
let forcedPasses = 0;
if (this.battle.requestState === "switch") {
const canSwitchOut = this.active.filter((pokemon) => pokemon?.switchFlag).length;
const canSwitchIn = this.pokemon.slice(this.active.length).filter((pokemon) => pokemon && !pokemon.fainted).length;
forcedSwitches = Math.min(canSwitchOut, canSwitchIn);
forcedPasses = canSwitchOut - forcedSwitches;
}
this.choice = {
cantUndo: false,
error: ``,
actions: [],
forcedSwitchesLeft: forcedSwitches,
forcedPassesLeft: forcedPasses,
switchIns: /* @__PURE__ */ new Set(),
zMove: false,
mega: false,
ultra: false,
dynamax: false,
terastallize: false
};
}
choose(input) {
if (!this.requestState) {
return this.emitChoiceError(
this.battle.ended ? `Can't do anything: The game is over` : `Can't do anything: It's not your turn`
);
}
if (this.choice.cantUndo) {
return this.emitChoiceError(`Can't undo: A trapping/disabling effect would cause undo to leak information`);
}
this.clearChoice();
const choiceStrings = input.startsWith("team ") ? [input] : input.split(",");
if (choiceStrings.length > this.active.length) {
return this.emitChoiceError(
`Can't make choices: You sent choices for ${choiceStrings.length} Pok\xE9mon, but this is a ${this.battle.gameType} game!`
);
}
for (const choiceString of choiceStrings) {
let [choiceType, data] = import_lib.Utils.splitFirst(choiceString.trim(), " ");
data = data.trim();
switch (choiceType) {
case "move":
const original = data;
const error = () => this.emitChoiceError(`Conflicting arguments for "move": ${original}`);
let targetLoc;
let event = "";
while (true) {
if (/\s(?:-|\+)?[1-3]$/.test(data) && (0, import_dex.toID)(data) !== "conversion2") {
if (targetLoc !== void 0)
return error();
targetLoc = parseInt(data.slice(-2));
data = data.slice(0, -2).trim();
} else if (data.endsWith(" mega")) {
if (event)
return error();
event = "mega";
data = data.slice(0, -5);
} else if (data.endsWith(" zmove")) {
if (event)
return error();
event = "zmove";
data = data.slice(0, -6);
} else if (data.endsWith(" ultra")) {
if (event)
return error();
event = "ultra";
data = data.slice(0, -6);
} else if (data.endsWith(" dynamax")) {
if (event)
return error();
event = "dynamax";
data = data.slice(0, -8);
} else if (data.endsWith(" gigantamax")) {
if (event)
return error();
event = "dynamax";
data = data.slice(0, -11);
} else if (data.endsWith(" max")) {
if (event)
return error();
event = "dynamax";
data = data.slice(0, -4);
} else if (data.endsWith(" terastal")) {
if (event)
return error();
event = "terastallize";
data = data.slice(0, -9);
} else if (data.endsWith(" terastallize")) {
if (event)
return error();
event = "terastallize";
data = data.slice(0, -13);
} else {
break;
}
}
if (!this.chooseMove(data, targetLoc, event))
return false;
break;
case "switch":
this.chooseSwitch(data);
break;
case "shift":
if (data)
return this.emitChoiceError(`Unrecognized data after "shift": ${data}`);
if (!this.chooseShift())
return false;
break;
case "team":
if (!this.chooseTeam(data))
return false;
break;
case "pass":
case "skip":
if (data)
return this.emitChoiceError(`Unrecognized data after "pass": ${data}`);
if (!this.choosePass())
return false;
break;
case "auto":
case "default":
this.autoChoose();
break;
default:
this.emitChoiceError(`Unrecognized choice: ${choiceString}`);
break;
}
}
return !this.choice.error;
}
getChoiceIndex(isPass) {
let index = this.choice.actions.length;
if (!isPass) {
switch (this.requestState) {
case "move":
while (index < this.active.length && (this.active[index].fainted || this.active[index].volatiles["commanding"])) {
this.choosePass();
index++;
}
break;
case "switch":
while (index < this.active.length && !this.active[index].switchFlag) {
this.choosePass();
index++;
}
break;
}
}
return index;
}
choosePass() {
const index = this.getChoiceIndex(true);
if (index >= this.active.length)
return false;
const pokemon = this.active[index];
switch (this.requestState) {
case "switch":
if (pokemon.switchFlag) {
if (!this.choice.forcedPassesLeft) {
return this.emitChoiceError(`Can't pass: You need to switch in a Pok\xE9mon to replace ${pokemon.name}`);
}
this.choice.forcedPassesLeft--;
}
break;
case "move":
break;
default:
return this.emitChoiceError(`Can't pass: Not a move or switch request`);
}
this.choice.actions.push({
choice: "pass"
});
return true;
}
/** Automatically finish a choice if not currently complete. */
autoChoose() {
if (this.requestState === "teampreview") {
if (!this.isChoiceDone())
this.chooseTeam();
} else if (this.requestState === "switch") {
let i = 0;
while (!this.isChoiceDone()) {
if (!this.chooseSwitch())
throw new Error(`autoChoose switch crashed: ${this.choice.error}`);
i++;
if (i > 10)
throw new Error(`autoChoose failed: infinite looping`);
}
} else if (this.requestState === "move") {
let i = 0;
while (!this.isChoiceDone()) {
if (!this.chooseMove())
throw new Error(`autoChoose crashed: ${this.choice.error}`);
i++;
if (i > 10)
throw new Error(`autoChoose failed: infinite looping`);
}
}
return true;
}
destroy() {
for (const pokemon of this.pokemon) {
if (pokemon)
pokemon.destroy();
}
for (const action of this.choice.actions) {
delete action.side;
delete action.pokemon;
delete action.target;
}
this.choice.actions = [];
this.pokemon = [];
this.active = [];
this.foe = null;
this.battle = null;
}
}
//# sourceMappingURL=side.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/side.ts"],
"sourcesContent": ["/**\r\n * Simulator Side\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * There's a lot of ambiguity between the terms \"player\", \"side\", \"team\",\r\n * and \"half-field\", which I'll try to explain here:\r\n *\r\n * These terms usually all mean the same thing. The exceptions are:\r\n *\r\n * - Multi-battle: there are 2 half-fields, 2 teams, 4 sides\r\n *\r\n * - Free-for-all: there are 2 half-fields, 4 teams, 4 sides\r\n *\r\n * \"Half-field\" is usually abbreviated to \"half\".\r\n *\r\n * Function naming will be very careful about which term to use. Pay attention\r\n * if it's relevant to your code.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Utils} from '../lib';\r\nimport type {RequestState} from './battle';\r\nimport {Pokemon, EffectState} from './pokemon';\r\nimport {State} from './state';\r\nimport {toID} from './dex';\r\n\r\n/** A single action that can be chosen. */\r\nexport interface ChosenAction {\r\n\tchoice: 'move' | 'switch' | 'instaswitch' | 'revivalblessing' | 'team' | 'shift' | 'pass'; \t// action type\r\n\tpokemon?: Pokemon; // the pokemon doing the action\r\n\ttargetLoc?: number; // relative location of the target to pokemon (move action only)\r\n\tmoveid: string; // a move to use (move action only)\r\n\tmove?: ActiveMove; // the active move corresponding to moveid (move action only)\r\n\ttarget?: Pokemon; // the target of the action\r\n\tindex?: number; // the chosen index in Team Preview\r\n\tside?: Side; // the action's side\r\n\tmega?: boolean | null; // true if megaing or ultra bursting\r\n\tzmove?: string; // if zmoving, the name of the zmove\r\n\tmaxMove?: string; // if dynamaxed, the name of the max move\r\n\tterastallize?: string; // if terastallizing, tera type\r\n\tpriority?: number; // priority of the action\r\n}\r\n\r\n/** What the player has chosen to happen. */\r\nexport interface Choice {\r\n\tcantUndo: boolean; // true if the choice can't be cancelled because of the maybeTrapped issue\r\n\terror: string; // contains error text in the case of a choice error\r\n\tactions: ChosenAction[]; // array of chosen actions\r\n\tforcedSwitchesLeft: number; // number of switches left that need to be performed\r\n\tforcedPassesLeft: number; // number of passes left that need to be performed\r\n\tswitchIns: Set<number>; // indexes of pokemon chosen to switch in\r\n\tzMove: boolean; // true if a Z-move has already been selected\r\n\tmega: boolean; // true if a mega evolution has already been selected\r\n\tultra: boolean; // true if an ultra burst has already been selected\r\n\tdynamax: boolean; // true if a dynamax has already been selected\r\n\tterastallize: boolean; // true if a terastallization has already been inputted\r\n}\r\n\r\nexport class Side {\r\n\treadonly battle: Battle;\r\n\treadonly id: SideID;\r\n\t/** Index in `battle.sides`: `battle.sides[side.n] === side` */\r\n\treadonly n: number;\r\n\r\n\tname: string;\r\n\tavatar: string;\r\n\tfoe: Side = null!; // set in battle.start()\r\n\t/** Only exists in multi battle, for the allied side */\r\n\tallySide: Side | null = null; // set in battle.start()\r\n\tteam: PokemonSet[];\r\n\tpokemon: Pokemon[];\r\n\tactive: Pokemon[];\r\n\r\n\tpokemonLeft: number;\r\n\tzMoveUsed: boolean;\r\n\t/**\r\n\t * This will be true in any gen before 8 or if the player (or their battle partner) has dynamaxed once already\r\n\t *\r\n\t * Use Side.canDynamaxNow() to check if a side can dynamax instead of this property because only one\r\n\t * player per team can dynamax on any given turn of a gen 8 Multi Battle.\r\n\t */\r\n\tdynamaxUsed: boolean;\r\n\r\n\tfaintedLastTurn: Pokemon | null;\r\n\tfaintedThisTurn: Pokemon | null;\r\n\ttotalFainted: number;\r\n\t/** only used by Gen 1 Counter */\r\n\tlastSelectedMove: ID = '';\r\n\r\n\t/** these point to the same object as the ally's, in multi battles */\r\n\tsideConditions: {[id: string]: EffectState};\r\n\tslotConditions: {[id: string]: EffectState}[];\r\n\r\n\tactiveRequest: AnyObject | null;\r\n\tchoice: Choice;\r\n\r\n\t/**\r\n\t * In gen 1, all lastMove stuff is tracked on Side rather than Pokemon\r\n\t * (this is for Counter and Mirror Move)\r\n\t * This is also used for checking Self-KO clause in Pokemon Stadium 2.\r\n\t */\r\n\tlastMove: Move | null;\r\n\r\n\tconstructor(name: string, battle: Battle, sideNum: number, team: PokemonSet[]) {\r\n\t\tconst sideScripts = battle.dex.data.Scripts.side;\r\n\t\tif (sideScripts) Object.assign(this, sideScripts);\r\n\r\n\t\tthis.battle = battle;\r\n\t\tthis.id = ['p1', 'p2', 'p3', 'p4'][sideNum] as SideID;\r\n\t\tthis.n = sideNum;\r\n\r\n\t\tthis.name = name;\r\n\t\tthis.avatar = '';\r\n\r\n\t\tthis.team = team;\r\n\t\tthis.pokemon = [];\r\n\t\tfor (let i = 0; i < this.team.length && i < 24; i++) {\r\n\t\t\t// console.log(\"NEW POKEMON: \" + (this.team[i] ? this.team[i].name : '[unidentified]'));\r\n\t\t\tthis.pokemon.push(new Pokemon(this.team[i], this));\r\n\t\t\tthis.pokemon[i].position = i;\r\n\t\t}\r\n\r\nLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,iBAAoB;AAEpB,qBAAmC;AACnC,mBAAoB;AACpB,iBAAmB;AAzBnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2DO,MAAM,KAAK;AAAA,EA6CjB,YAAY,MAAc,QAAgB,SAAiB,MAAoB;AArC/E,eAAY;AAEZ;AAAA;AAAA,oBAAwB;AAmBxB;AAAA,4BAAuB;AAiBtB,UAAM,cAAc,OAAO,IAAI,KAAK,QAAQ;AAC5C,QAAI;AAAa,aAAO,OAAO,MAAM,WAAW;AAEhD,SAAK,SAAS;AACd,SAAK,KAAK,CAAC,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO;AAC1C,SAAK,IAAI;AAET,SAAK,OAAO;AACZ,SAAK,SAAS;AAEd,SAAK,OAAO;AACZ,SAAK,UAAU,CAAC;AAChB,aAAS,IAAI,GAAG,IAAI,KAAK,KAAK,UAAU,IAAI,IAAI,KAAK;AAEpD,WAAK,QAAQ,KAAK,IAAI,uBAAQ,KAAK,KAAK,CAAC,GAAG,IAAI,CAAC;AACjD,WAAK,QAAQ,CAAC,EAAE,WAAW;AAAA,IAC5B;AAEA,YAAQ,KAAK,OAAO,UAAU;AAAA,MAC9B,KAAK;AACJ,aAAK,SAAS,CAAC,MAAO,IAAK;AAC3B;AAAA,MACD,KAAK;AAAA,MAAW,KAAK;AACpB,aAAK,SAAS,CAAC,MAAO,MAAO,IAAK;AAClC;AAAA,MACD;AACC,aAAK,SAAS,CAAC,IAAK;AAAA,IACrB;AAEA,SAAK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;
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 state_exports = {};
__export(state_exports, {
State: () => State
});
module.exports = __toCommonJS(state_exports);
var import_battle = require("./battle");
var import_dex = require("./dex");
var import_field = require("./field");
var import_pokemon = require("./pokemon");
var import_prng = require("./prng");
var import_side = require("./side");
/**
* Simulator State
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Helper functions for serializing Battle instances to JSON and back.
*
* (You might also consider using input logs instead.)
*
* @license MIT
*/
const POSITIONS = "abcdefghijklmnopqrstuvwx";
const BATTLE = /* @__PURE__ */ new Set([
"dex",
"gen",
"ruleTable",
"id",
"log",
"inherit",
"format",
"teamGenerator",
"HIT_SUBSTITUTE",
"NOT_FAIL",
"FAIL",
"SILENT_FAIL",
"field",
"sides",
"prng",
"hints",
"deserialized",
"queue",
"actions"
]);
const FIELD = /* @__PURE__ */ new Set(["id", "battle"]);
const SIDE = /* @__PURE__ */ new Set(["battle", "team", "pokemon", "choice", "activeRequest"]);
const POKEMON = /* @__PURE__ */ new Set([
"side",
"battle",
"set",
"name",
"fullname",
"id",
"happiness",
"level",
"pokeball",
"baseMoveSlots"
]);
const CHOICE = /* @__PURE__ */ new Set(["switchIns"]);
const ACTIVE_MOVE = /* @__PURE__ */ new Set(["move"]);
const State = new class {
serializeBattle(battle) {
const state = this.serialize(battle, BATTLE, battle);
state.field = this.serializeField(battle.field);
state.sides = new Array(battle.sides.length);
for (const [i, side] of battle.sides.entries()) {
state.sides[i] = this.serializeSide(side);
}
state.prng = battle.prng.seed;
state.hints = Array.from(battle.hints);
state.log = battle.log;
state.queue = this.serializeWithRefs(battle.queue.list, battle);
state.formatid = battle.format.id;
return state;
}
// Deserialization can only really be done on the root Battle object as
// the leaf nodes like Side or Pokemon contain backreferences to Battle
// but don't contain the information to fill it in because the cycles in
// the graph have been serialized as references. Once deserialzized, the
// Battle can then be restarted (and provided with a `send` function for
// receiving updates).
deserializeBattle(serialized) {
const state = typeof serialized === "string" ? JSON.parse(serialized) : serialized;
const options = {
formatid: state.formatid,
seed: state.prngSeed,
rated: state.rated,
debug: state.debugMode,
// We need to tell the Battle that we're creating that it's been
// deserialized so that it allows us to populate it correctly and
// doesn't attempt to start playing out until we're ready.
deserialized: true,
strictChoices: state.strictChoices
};
for (const side of state.sides) {
const team = side.team.split(side.team.length > 9 ? "," : "");
options[side.id] = {
name: side.name,
avatar: side.avatar,
team: team.map((p) => side.pokemon[Number(p) - 1].set)
};
}
const battle = new import_battle.Battle(options);
for (const [i, s] of state.sides.entries()) {
const side = battle.sides[i];
const ordered = new Array(side.pokemon.length);
const team = s.team.split(s.team.length > 9 ? "," : "");
for (const [j, pos] of team.entries()) {
ordered[Number(pos) - 1] = side.pokemon[j];
}
side.pokemon = ordered;
}
this.deserialize(state, battle, BATTLE, battle);
this.deserializeField(state.field, battle.field);
let activeRequests = false;
for (const [i, side] of state.sides.entries()) {
this.deserializeSide(side, battle.sides[i]);
activeRequests = activeRequests || side.activeRequest === void 0;
}
if (activeRequests) {
const requests = battle.getRequests(battle.requestState);
for (const [i, side] of state.sides.entries()) {
battle.sides[i].activeRequest = side.activeRequest === null ? null : requests[i];
}
}
battle.prng = new import_prng.PRNG(state.prng);
const queue = this.deserializeWithRefs(state.queue, battle);
battle.queue.list = queue;
battle.hints = new Set(state.hints);
battle.log = state.log;
return battle;
}
// Direct comparsions of serialized state will be flakey as the timestamp
// protocol message |t:| can diverge between two different runs over the same state.
// State must first be normalized before it is comparable.
normalize(state) {
state.log = this.normalizeLog(state.log);
return state;
}
normalizeLog(log) {
if (!log)
return log;
const normalized = (typeof log === "string" ? log.split("\n") : log).map((line) => line.startsWith(`|t:|`) ? `|t:|` : line);
return typeof log === "string" ? normalized.join("\n") : normalized;
}
serializeField(field) {
return this.serialize(field, FIELD, field.battle);
}
deserializeField(state, field) {
this.deserialize(state, field, FIELD, field.battle);
}
serializeSide(side) {
const state = this.serialize(side, SIDE, side.battle);
state.pokemon = new Array(side.pokemon.length);
const team = new Array(side.pokemon.length);
for (const [i, pokemon] of side.pokemon.entries()) {
state.pokemon[i] = this.serializePokemon(pokemon);
team[side.team.indexOf(pokemon.set)] = i + 1;
}
state.team = team.join(team.length > 9 ? "," : "");
state.choice = this.serializeChoice(side.choice, side.battle);
if (side.activeRequest === null)
state.activeRequest = null;
return state;
}
deserializeSide(state, side) {
this.deserialize(state, side, SIDE, side.battle);
for (const [i, pokemon] of state.pokemon.entries()) {
this.deserializePokemon(pokemon, side.pokemon[i]);
}
this.deserializeChoice(state.choice, side.choice, side.battle);
}
serializePokemon(pokemon) {
const state = this.serialize(pokemon, POKEMON, pokemon.battle);
state.set = pokemon.set;
if (pokemon.baseMoveSlots.length !== pokemon.moveSlots.length || !pokemon.baseMoveSlots.every((ms, i) => ms === pokemon.moveSlots[i])) {
state.baseMoveSlots = this.serializeWithRefs(pokemon.baseMoveSlots, pokemon.battle);
}
return state;
}
deserializePokemon(state, pokemon) {
this.deserialize(state, pokemon, POKEMON, pokemon.battle);
pokemon.set = state.set;
let baseMoveSlots;
if (state.baseMoveSlots) {
baseMoveSlots = this.deserializeWithRefs(state.baseMoveSlots, pokemon.battle);
for (const [i, baseMoveSlot] of baseMoveSlots.entries()) {
const moveSlot = pokemon.moveSlots[i];
if (moveSlot.id === baseMoveSlot.id && !moveSlot.virtual) {
baseMoveSlots[i] = moveSlot;
}
}
} else {
baseMoveSlots = pokemon.moveSlots.slice();
}
pokemon.baseMoveSlots = baseMoveSlots;
if (state.showCure === void 0)
pokemon.showCure = void 0;
}
serializeChoice(choice, battle) {
const state = this.serialize(choice, CHOICE, battle);
state.switchIns = Array.from(choice.switchIns);
return state;
}
deserializeChoice(state, choice, battle) {
this.deserialize(state, choice, CHOICE, battle);
choice.switchIns = new Set(state.switchIns);
}
// Simply looking for a 'hit' field to determine if an object is an ActiveMove or not seems
// pretty fragile, but its no different than what the simulator is doing. We go further and
// also check if the object has an 'id', as that's what we will intrepret as the Move.
isActiveMove(obj) {
return obj.hasOwnProperty("hit") && (obj.hasOwnProperty("id") || obj.hasOwnProperty("move"));
}
// ActiveMove is somewhat problematic (#5415) as it sometimes extends a Move and adds on
// some mutable fields. We'd like to avoid displaying all the readonly fields of Move
// (which in theory should not be changed by the ActiveMove...), so we collapse them
// into a 'move: [Move:...]' reference. If isActiveMove returns a false positive *and*
// and object contains an 'id' field matching a Move *and* it contains fields with the
// same name as said Move then we'll miss them during serialization and won't
// deserialize properly. This is unlikely to be the case, and would probably indicate
// a bug in the simulator if it ever happened, but if not, the isActiveMove check can
// be extended.
serializeActiveMove(move, battle) {
const base = battle.dex.moves.get(move.id);
const skip = /* @__PURE__ */ new Set([...ACTIVE_MOVE]);
for (const [key, value] of Object.entries(base)) {
if (typeof value === "object" || move[key] === value)
skip.add(key);
}
const state = this.serialize(move, skip, battle);
state.move = `[Move:${move.id}]`;
return state;
}
deserializeActiveMove(state, battle) {
const move = battle.dex.getActiveMove(this.fromRef(state.move, battle));
this.deserialize(state, move, ACTIVE_MOVE, battle);
return move;
}
serializeWithRefs(obj, battle) {
switch (typeof obj) {
case "function":
return void 0;
case "undefined":
case "boolean":
case "number":
case "string":
return obj;
case "object":
if (obj === null)
return null;
if (Array.isArray(obj)) {
const arr = new Array(obj.length);
for (const [i, o2] of obj.entries()) {
arr[i] = this.serializeWithRefs(o2, battle);
}
return arr;
}
if (this.isActiveMove(obj))
return this.serializeActiveMove(obj, battle);
if (this.isReferable(obj))
return this.toRef(obj);
if (obj.constructor !== Object) {
throw new TypeError(`Unsupported type ${obj.constructor.name}: ${obj}`);
}
const o = {};
for (const [key, value] of Object.entries(obj)) {
o[key] = this.serializeWithRefs(value, battle);
}
return o;
default:
throw new TypeError(`Unexpected typeof === '${typeof obj}': ${obj}`);
}
}
deserializeWithRefs(obj, battle) {
switch (typeof obj) {
case "undefined":
case "boolean":
case "number":
return obj;
case "string":
return this.fromRef(obj, battle) || obj;
case "object":
if (obj === null)
return null;
if (Array.isArray(obj)) {
const arr = new Array(obj.length);
for (const [i, o2] of obj.entries()) {
arr[i] = this.deserializeWithRefs(o2, battle);
}
return arr;
}
if (this.isActiveMove(obj))
return this.deserializeActiveMove(obj, battle);
const o = {};
for (const [key, value] of Object.entries(obj)) {
o[key] = this.deserializeWithRefs(value, battle);
}
return o;
case "function":
default:
throw new TypeError(`Unexpected typeof === '${typeof obj}': ${obj}`);
}
}
isReferable(obj) {
if (!this.REFERABLE) {
this.REFERABLE = /* @__PURE__ */ new Set([
import_battle.Battle,
import_field.Field,
import_side.Side,
import_pokemon.Pokemon,
import_dex.Dex.Condition,
import_dex.Dex.Ability,
import_dex.Dex.Item,
import_dex.Dex.Move,
import_dex.Dex.Species
]);
}
return this.REFERABLE.has(obj.constructor);
}
toRef(obj) {
const id = obj instanceof import_pokemon.Pokemon ? `${obj.side.id}${POSITIONS[obj.position]}` : `${obj.id}`;
return `[${obj.constructor.name}${id ? ":" : ""}${id}]`;
}
fromRef(ref, battle) {
if (!ref.startsWith("[") && !ref.endsWith("]"))
return void 0;
ref = ref.substring(1, ref.length - 1);
if (ref === "Battle")
return battle;
if (ref === "Field")
return battle.field;
const [type, id] = ref.split(":");
switch (type) {
case "Side":
return battle.sides[Number(id[1]) - 1];
case "Pokemon":
return battle.sides[Number(id[1]) - 1].pokemon[POSITIONS.indexOf(id[2])];
case "Ability":
return battle.dex.abilities.get(id);
case "Item":
return battle.dex.items.get(id);
case "Move":
return battle.dex.moves.get(id);
case "Condition":
return battle.dex.conditions.get(id);
case "Species":
return battle.dex.species.get(id);
default:
return void 0;
}
}
serialize(obj, skip, battle) {
const state = {};
for (const [key, value] of Object.entries(obj)) {
if (skip.has(key))
continue;
const val = this.serializeWithRefs(value, battle);
if (typeof val !== "undefined")
state[key] = val;
}
return state;
}
deserialize(state, obj, skip, battle) {
for (const [key, value] of Object.entries(state)) {
if (skip.has(key))
continue;
obj[key] = this.deserializeWithRefs(value, battle);
}
}
}();
//# sourceMappingURL=state.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/state.ts"],
"sourcesContent": ["/**\r\n * Simulator State\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Helper functions for serializing Battle instances to JSON and back.\r\n *\r\n * (You might also consider using input logs instead.)\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Battle} from './battle';\r\nimport {Dex} from './dex';\r\nimport {Field} from './field';\r\nimport {Pokemon} from './pokemon';\r\nimport {PRNG} from './prng';\r\nimport {Choice, Side} from './side';\r\n\r\n// The simulator supports up to 24 different Pokemon on a team. Serialization\r\n// uses letters instead of numbers to indicate indices/positions, but where\r\n// the simulator only gives a position to active Pokemon, serialization\r\n// uses letters for every Pokemon on a team. Active pokemon will still\r\n// have the same letter as their position would indicate, but non-active\r\n// team members are filled in with subsequent letters.\r\nconst POSITIONS = 'abcdefghijklmnopqrstuvwx';\r\n\r\n// Several types we serialize as 'references' in the form '[Type]' because\r\n// they are either circular or they are (or at least, should be) immutable\r\n// and thus can simply be reconsituted as needed.\r\n// NOTE: Species is not strictly immutable as some OM formats rely on an\r\n// onModifySpecies event - deserialization is not possible for such formats.\r\ntype Referable = Battle | Field | Side | Pokemon | Condition | Ability | Item | Move | Species;\r\n\r\n// Certain fields are either redundant (transient caches, constants, duplicate\r\n// information) or require special treatment. These sets contain the specific\r\n// keys which we skip during default (de)serialization and (the keys which)\r\n// need special treatment from these sets are then handled manually.\r\n\r\nconst BATTLE = new Set([\r\n\t'dex', 'gen', 'ruleTable', 'id', 'log', 'inherit', 'format', 'teamGenerator',\r\n\t'HIT_SUBSTITUTE', 'NOT_FAIL', 'FAIL', 'SILENT_FAIL', 'field', 'sides', 'prng', 'hints',\r\n\t'deserialized', 'queue', 'actions',\r\n]);\r\nconst FIELD = new Set(['id', 'battle']);\r\nconst SIDE = new Set(['battle', 'team', 'pokemon', 'choice', 'activeRequest']);\r\nconst POKEMON = new Set([\r\n\t'side', 'battle', 'set', 'name', 'fullname', 'id',\r\n\t'happiness', 'level', 'pokeball', 'baseMoveSlots',\r\n]);\r\nconst CHOICE = new Set(['switchIns']);\r\nconst ACTIVE_MOVE = new Set(['move']);\r\n\r\nexport const State = new class {\r\n\t// REFERABLE is used to determine which objects are of the Referable type by\r\n\t// comparing their constructors. Unfortunately, we need to set this dynamically\r\n\t// due to circular module dependencies on Battle and Field instead\r\n\t// of simply initializing it as a const. See isReferable for where this\r\n\t// gets lazily created on demand.\r\n\t// eslint-disable-next-line @typescript-eslint/ban-types\r\n\tREFERABLE?: Set<Function>;\r\n\r\n\tserializeBattle(battle: Battle): /* Battle */ AnyObject {\r\n\t\tconst state: /* Battle */ AnyObject = this.serialize(battle, BATTLE, battle);\r\n\t\tstate.field = this.serializeField(battle.field);\r\n\t\tstate.sides = new Array(battle.sides.length);\r\n\t\tfor (const [i, side] of battle.sides.entries()) {\r\n\t\t\tstate.sides[i] = this.serializeSide(side);\r\n\t\t}\r\n\t\tstate.prng = battle.prng.seed;\r\n\t\tstate.hints = Array.from(battle.hints);\r\n\t\t// We treat log specially because we only set it back on Battle after everything\r\n\t\t// else has been deserialized to avoid anything accidentally `add`-ing to it.\r\n\t\tstate.log = battle.log;\r\n\t\tstate.queue = this.serializeWithRefs(battle.queue.list, battle);\r\n\t\tstate.formatid = battle.format.id;\r\n\t\treturn state;\r\n\t}\r\n\r\n\t// Deserialization can only really be done on the root Battle object as\r\n\t// the leaf nodes like Side or Pokemon contain backreferences to Battle\r\n\t// but don't contain the information to fill it in because the cycles in\r\n\t// the graph have been serialized as references. Once deserialzized, the\r\n\t// Battle can then be restarted (and provided with a `send` function for\r\n\t// receiving updates).\r\n\tdeserializeBattle(serialized: string | /* Battle */ AnyObject): Battle {\r\n\t\tconst state: /* Battle */ AnyObject =\r\n\t\t\ttypeof serialized === 'string' ? JSON.parse(serialized) : serialized;\r\n\t\tconst options = {\r\n\t\t\tformatid: state.formatid,\r\n\t\t\tseed: state.prngSeed,\r\n\t\t\trated: state.rated,\r\n\t\t\tdebug: state.debugMode,\r\n\t\t\t// We need to tell the Battle that we're creating that it's been\r\n\t\t\t// deserialized so that it allows us to populate it correctly and\r\n\t\t\t// doesn't attempt to start playing out until we're ready.\r\n\t\t\tdeserialized: true,\r\n\t\t\tstrictChoices: state.strictChoices,\r\n\t\t};\r\n\t\tfor (const side of state.sides) {\r\n\t\t\t// When we instantiate the Battle again we need the pokemon to be in\r\n\t\t\t// the correct order they were in at the start of the Battle which was\r\n\t\t\t// serialized. See serializeLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,oBAAqB;AACrB,iBAAkB;AAClB,mBAAoB;AACpB,qBAAsB;AACtB,kBAAmB;AACnB,kBAA2B;AAhB3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,MAAM,YAAY;AAclB,MAAM,SAAS,oBAAI,IAAI;AAAA,EACtB;AAAA,EAAO;AAAA,EAAO;AAAA,EAAa;AAAA,EAAM;AAAA,EAAO;AAAA,EAAW;AAAA,EAAU;AAAA,EAC7D;AAAA,EAAkB;AAAA,EAAY;AAAA,EAAQ;AAAA,EAAe;AAAA,EAAS;AAAA,EAAS;AAAA,EAAQ;AAAA,EAC/E;AAAA,EAAgB;AAAA,EAAS;AAC1B,CAAC;AACD,MAAM,QAAQ,oBAAI,IAAI,CAAC,MAAM,QAAQ,CAAC;AACtC,MAAM,OAAO,oBAAI,IAAI,CAAC,UAAU,QAAQ,WAAW,UAAU,eAAe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M,YAAY,MAAM,KAAK,OAAO,SAAS;AAC7C,WAAO;AAAA,EACR;AAAA,EAEA,kBAAkB,OAA+B,QAAgB,QAAgB;AAChF,SAAK,YAAY,OAAO,QAAQ,QAAQ,MAAM;AAC9C,WAAO,YAAY,IAAI,IAAI,MAAM,SAAS;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,KAAmC;AAC/C,WAAO,IAAI,eAAe,KAAK,MAAM,IAAI,eAAe,IAAI,KAAK,IAAI,eAAe,MAAM;AAAA,EAC3F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,oBAAoB,MAAkB,QLine truncated
"names": ["o"]
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/team-validator.ts"],
"sourcesContent": ["/**\r\n * Team Validator\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Handles team validation, and specifically learnset checking.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Dex, toID} from './dex';\r\nimport {Utils} from '../lib';\r\nimport {Tags} from '../data/tags';\r\nimport {Teams} from './teams';\r\nimport {PRNG} from './prng';\r\n\r\n/**\r\n * Describes a possible way to get a pokemon. Is not exhaustive!\r\n * sourcesBefore covers all sources that do not have exclusive\r\n * moves (like catching wild pokemon).\r\n *\r\n * First character is a generation number, 1-8.\r\n * Second character is a source ID, one of:\r\n *\r\n * - E = egg, 3rd char+ is the father in gen 2-5, empty in gen 6-7\r\n * because egg moves aren't restricted to fathers anymore\r\n * - S = event, 3rd char+ is the index in .eventData\r\n * - D = Dream World, only 5D is valid\r\n * - V = Virtual Console or Let's Go transfer, only 7V/8V is valid\r\n *\r\n * Designed to match MoveSource where possible.\r\n */\r\nexport type PokemonSource = string;\r\n\r\n/**\r\n * Represents a set of possible ways to get a Pok\u00E9mon with a given\r\n * set.\r\n *\r\n * `new PokemonSources()` creates an empty set;\r\n * `new PokemonSources(dex.gen)` allows all Pokemon.\r\n *\r\n * The set mainly stored as an Array `sources`, but for sets that\r\n * could be sourced from anywhere (for instance, TM moves), we\r\n * instead just set `sourcesBefore` to a number meaning \"any\r\n * source at or before this gen is possible.\"\r\n *\r\n * In other words, this variable represents the set of all\r\n * sources in `sources`, union all sources at or before\r\n * gen `sourcesBefore`.\r\n */\r\nexport class PokemonSources {\r\n\t/**\r\n\t * A set of specific possible PokemonSources; implemented as\r\n\t * an Array rather than a Set for perf reasons.\r\n\t */\r\n\tsources: PokemonSource[];\r\n\t/**\r\n\t * if nonzero: the set also contains all possible sources from\r\n\t * this gen and earlier.\r\n\t */\r\n\tsourcesBefore: number;\r\n\t/**\r\n\t * the set requires sources from this gen or later\r\n\t * this should be unchanged from the format's minimum past gen\r\n\t * (3 in modern games, 6 if pentagon is required, etc)\r\n\t */\r\n\tsourcesAfter: number;\r\n\tisHidden: boolean | null;\r\n\t/**\r\n\t * `limitedEggMoves` is a list of moves that can only be obtained from an\r\n\t * egg with another father in gen 2-5. If there are multiple such moves,\r\n\t * potential fathers need to be checked to see if they can actually\r\n\t * learn the move combination in question.\r\n\t *\r\n\t * `null` = the current move is definitely not a limited egg move\r\n\t *\r\n\t * `undefined` = the current move may or may not be a limited egg move\r\n\t */\r\n\tlimitedEggMoves?: ID[] | null;\r\n\t/**\r\n\t * Some Pokemon evolve by having a move in their learnset (like Piloswine\r\n\t * with Ancient Power). These can only carry three other moves from their\r\n\t * prevo, because the fourth move must be the evo move. This restriction\r\n\t * doesn't apply to gen 6+ eggs, which can get around the restriction with\r\n\t * the relearner.\r\n\t */\r\n\tmoveEvoCarryCount: number;\r\n\r\n\tbabyOnly?: string;\r\n\tsketchMove?: string;\r\n\tdreamWorldMoveCount: number;\r\n\thm?: string;\r\n\trestrictiveMoves?: string[];\r\n\t/** Obscure learn methods */\r\n\trestrictedMove?: ID;\r\n\r\n\tconstructor(sourcesBefore = 0, sourcesAfter = 0) {\r\n\t\tthis.sources = [];\r\n\t\tthis.sourcesBefore = sourcesBefore;\r\n\t\tthis.sourcesAfter = sourcesAfter;\r\n\t\tthis.isHidden = null;\r\n\t\tthis.limitedEggMoves = undefined;\r\n\t\tthis.moveEvoCarryCount = 0;\r\n\t\tthis.dreamWorldMoveCount = 0;\r\n\t}\r\n\tsize() {\r\n\t\tif (this.sourcesBefore) return Infinity;\r\n\t\treturn this.sources.length;\r\n\t}\r\n\tadd(source: PokemonSource, limitedEggMove?: ID | null) {\r\n\t\tif (this.sources[this.sources.length - 1] !== source) this.sources.push(source);\r\n\t\tif (limitedEggMove && this.limitedEggMoves !== null) {\r\n\t\t\tthis.limitedEggMoves = [limitedEggMove];\r\n\t\t} else if (limitedEggMove === null) {\r\n\t\t\tthis.limitedEggMoves = null;\r\n\t\t}\r\n\t}\r\n\taddGen(sourceGen: number) {\r\n\t\tthis.sourcesBefore = Math.max(this.sourcesBefore, sourceGen);\r\n\t\tthis.limitedEggMoves = null;\r\n\t}\r\n\tminSourceGen() {\r\n\t\tif (this.sourcesBefore) return this.sourcesAfter || 1;\r\n\t\tlet min = 10;\r\n\t\tfor (const source of this.sources) {\r\n\t\t\tconst sourceGen = parseInt(source.charAt(0));\r\n\t\t\tif (sourceGen < min) min = sourceGen;\r\n\t\t}\r\n\t\tif (min === 10) return 0;\r\n\t\treturn min;\r\n\t}\r\n\tmaxSourceGen() {\r\n\t\tlet max = this.sourcesBefore;\r\n\t\tfor (const source of this.sources) {\r\n\t\t\tconst sourceGen = parseInt(source.charAt(0));\r\n\t\t\tif (sourceGen > max) max = sourceGen;\r\n\t\t}\r\n\t\treturn max;\r\n\t}\r\n\tintersectWith(other: PokemonSources) {\r\n\t\tif (other.sourcesBefore || this.sourcesBefore) {\r\n\t\t\t// Line truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,iBAAwB;AACxB,iBAAoB;AACpB,kBAAmB;AACnB,mBAAoB;AACpB,kBAAmB;AAbnB;AAAA;AAAA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AAQ,IAAI,IAAI,IAAI,GAAG,QAAQ;AACnG,cAAI,OAAO,aAAa;AAAA,QACzB,OAAO;AACN,cAAI,OAAO,QAAQ;AACnB,cAAI,QAAQ,gBAAgB;AAAS,gBAAI,UAAU;AAAA,QACpD;AAAA,MACD;AAAA,IACD;AAEA,eAAW,CAAC,MAAM,QAAQ,OAAO,IAAI,KAAK,UAAU,iBAAiB;AACpE,UAAI,QAAQ;AACZ,iBAAW,OAAO,MAAM;AACvB,YAAI,QAAQ,GAAG,IAAI,GAAG;AACrB,mBAAS,QAAQ,QAAQ,GAAG,IAAI;AAAA,QACjC;AAAA,MACD;AACA,UAAI,SAAS,QAAQ,OAAO;AAC3B,cAAM,SAAS,SAAS,OAAO,WAAW;AAC1C,iBAAS,KAAK,sBAAsB,YAAY,OAAO,SAAS;AAAA,MACjE,WAAW,CAAC,SAAS,SAAS,KAAK,QAAQ;AAC1C,cAAM,SAAS,SAAS,OAAO,WAAW;AAC1C,iBAAS,KAAK,oCAAoC,wBAAwB,SAAS;AAAA,MACpF;AAAA,IACD;AAEA,eAAW,QAAQ,UAAU,KAAK,GAAG;AACpC,UAAI,MAAM,SAAS,KAAK,OAAO,CAAC,CAAC;AAAG;AACpC,YAAM,YAAY,Line truncated
"names": []
}
+557
View File
@@ -0,0 +1,557 @@
"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 teams_exports = {};
__export(teams_exports, {
Teams: () => Teams,
default: () => teams_default
});
module.exports = __toCommonJS(teams_exports);
var import_dex = require("./dex");
/**
* Teams
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Functions for converting and generating teams.
*
* @license MIT
*/
const Teams = new class Teams2 {
pack(team) {
if (!team)
return "";
function getIv(ivs, s) {
return ivs[s] === 31 || ivs[s] === void 0 ? "" : ivs[s].toString();
}
let buf = "";
for (const set of team) {
if (buf)
buf += "]";
buf += set.name || set.species;
const id = this.packName(set.species || set.name);
buf += "|" + (this.packName(set.name || set.species) === id ? "" : id);
buf += "|" + this.packName(set.item);
buf += "|" + this.packName(set.ability);
buf += "|" + set.moves.map(this.packName).join(",");
buf += "|" + (set.nature || "");
let evs = "|";
if (set.evs) {
evs = "|" + (set.evs["hp"] || "") + "," + (set.evs["atk"] || "") + "," + (set.evs["def"] || "") + "," + (set.evs["spa"] || "") + "," + (set.evs["spd"] || "") + "," + (set.evs["spe"] || "");
}
if (evs === "|,,,,,") {
buf += "|";
} else {
buf += evs;
}
if (set.gender) {
buf += "|" + set.gender;
} else {
buf += "|";
}
let ivs = "|";
if (set.ivs) {
ivs = "|" + getIv(set.ivs, "hp") + "," + getIv(set.ivs, "atk") + "," + getIv(set.ivs, "def") + "," + getIv(set.ivs, "spa") + "," + getIv(set.ivs, "spd") + "," + getIv(set.ivs, "spe");
}
if (ivs === "|,,,,,") {
buf += "|";
} else {
buf += ivs;
}
if (set.shiny) {
buf += "|S";
} else {
buf += "|";
}
if (set.level && set.level !== 100) {
buf += "|" + set.level;
} else {
buf += "|";
}
if (set.happiness !== void 0 && set.happiness !== 255) {
buf += "|" + set.happiness;
} else {
buf += "|";
}
if (set.pokeball || set.hpType || set.gigantamax || set.dynamaxLevel !== void 0 && set.dynamaxLevel !== 10 || set.teraType) {
buf += "," + this.packName(set.pokeball || "");
buf += "," + (set.hpType || "");
buf += "," + (set.gigantamax ? "G" : "");
buf += "," + (set.dynamaxLevel !== void 0 && set.dynamaxLevel !== 10 ? set.dynamaxLevel : "");
buf += "," + (set.teraType || "");
}
}
return buf;
}
unpack(buf) {
if (!buf)
return null;
if (typeof buf !== "string")
return buf;
if (buf.startsWith("[") && buf.endsWith("]")) {
try {
buf = this.pack(JSON.parse(buf));
} catch {
return null;
}
}
const team = [];
let i = 0;
let j = 0;
for (let count = 0; count < 24; count++) {
const set = {};
team.push(set);
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.name = buf.substring(i, j);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.species = this.unpackName(buf.substring(i, j), import_dex.Dex.species) || set.name;
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.uuid = buf.substring(i, j);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.currentHealth = parseInt(buf.substring(i, j));
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.status = buf.substring(i, j);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.statusDuration = parseInt(buf.substring(i, j));
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.item = this.unpackName(buf.substring(i, j), import_dex.Dex.items);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
const ability = buf.substring(i, j);
set.ability = this.unpackName(ability, import_dex.Dex.abilities);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.moves = buf.substring(i, j).split(",", 24).map((name) => this.unpackName(name, import_dex.Dex.moves));
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.movesInfo = buf.substring(i, j).split(",", 24).map((moveData) => {
const moveInfo = {};
let data = moveData.split("/");
moveInfo.pp = parseInt(data[0]);
moveInfo.maxPp = parseInt(data[1]);
return moveInfo;
});
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
set.nature = this.unpackName(buf.substring(i, j), import_dex.Dex.natures);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
if (j !== i) {
const evs = buf.substring(i, j).split(",", 6);
set.evs = {
hp: Number(evs[0]) || 0,
atk: Number(evs[1]) || 0,
def: Number(evs[2]) || 0,
spa: Number(evs[3]) || 0,
spd: Number(evs[4]) || 0,
spe: Number(evs[5]) || 0
};
}
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
if (i !== j)
set.gender = buf.substring(i, j);
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
if (j !== i) {
const ivs = buf.substring(i, j).split(",", 6);
set.ivs = {
hp: ivs[0] === "" ? 31 : Number(ivs[0]) || 0,
atk: ivs[1] === "" ? 31 : Number(ivs[1]) || 0,
def: ivs[2] === "" ? 31 : Number(ivs[2]) || 0,
spa: ivs[3] === "" ? 31 : Number(ivs[3]) || 0,
spd: ivs[4] === "" ? 31 : Number(ivs[4]) || 0,
spe: ivs[5] === "" ? 31 : Number(ivs[5]) || 0
};
}
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
if (i !== j)
set.shiny = true;
i = j + 1;
j = buf.indexOf("|", i);
if (j < 0)
return null;
if (i !== j)
set.level = parseInt(buf.substring(i, j));
i = j + 1;
j = buf.indexOf("]", i);
let misc;
if (j < 0) {
if (i < buf.length)
misc = buf.substring(i).split(",", 6);
} else {
if (i !== j)
misc = buf.substring(i, j).split(",", 6);
}
if (misc) {
set.happiness = misc[0] ? Number(misc[0]) : 255;
set.pokeball = this.unpackName(misc[1] || "", import_dex.Dex.items);
set.hpType = misc[2] || "";
set.gigantamax = !!misc[3];
set.dynamaxLevel = misc[4] ? Number(misc[4]) : 10;
set.teraType = misc[5];
}
if (j < 0)
break;
i = j + 1;
}
return team;
}
/** Very similar to toID but without the lowercase conversion */
packName(name) {
if (!name)
return "";
return name.replace(/[^A-Za-z0-9]+/g, "");
}
/** Will not entirely recover a packed name, but will be a pretty readable guess */
unpackName(name, dexTable) {
if (!name)
return "";
if (dexTable) {
const obj = dexTable.get(name);
if (obj.exists)
return obj.name;
}
return name.replace(/([0-9]+)/g, " $1 ").replace(/([A-Z])/g, " $1").replace(/[ ][ ]/g, " ").trim();
}
/**
* Exports a team in human-readable PS export format
*/
export(team, options) {
let output = "";
for (const set of team) {
output += this.exportSet(set, options) + `
`;
}
return output;
}
exportSet(set, { hideStats } = {}) {
let out = ``;
if (set.name && set.name !== set.species) {
out += `${set.name} (${set.species})`;
} else {
out += set.species;
}
if (set.gender === "M")
out += ` (M)`;
if (set.gender === "F")
out += ` (F)`;
if (set.item)
out += ` @ ${set.item}`;
out += `
`;
if (set.ability) {
out += `Ability: ${set.ability}
`;
}
if (set.level && set.level !== 100) {
out += `Level: ${set.level}
`;
}
if (set.shiny) {
out += `Shiny: Yes
`;
}
if (typeof set.happiness === "number" && set.happiness !== 255 && !isNaN(set.happiness)) {
out += `Happiness: ${set.happiness}
`;
}
if (set.pokeball) {
out += `Pokeball: ${set.pokeball}
`;
}
if (set.hpType) {
out += `Hidden Power: ${set.hpType}
`;
}
if (typeof set.dynamaxLevel === "number" && set.dynamaxLevel !== 10 && !isNaN(set.dynamaxLevel)) {
out += `Dynamax Level: ${set.dynamaxLevel}
`;
}
if (set.gigantamax) {
out += `Gigantamax: Yes
`;
}
if (set.teraType) {
out += `Tera Type: ${set.teraType}
`;
}
if (!hideStats) {
if (set.evs) {
const stats = import_dex.Dex.stats.ids().map(
(stat) => set.evs[stat] ? `${set.evs[stat]} ${import_dex.Dex.stats.shortNames[stat]}` : ``
).filter(Boolean);
if (stats.length) {
out += `EVs: ${stats.join(" / ")}
`;
}
}
if (set.nature) {
out += `${set.nature} Nature
`;
}
if (set.ivs) {
const stats = import_dex.Dex.stats.ids().map(
(stat) => set.ivs[stat] !== 31 && set.ivs[stat] !== void 0 ? `${set.ivs[stat] || 0} ${import_dex.Dex.stats.shortNames[stat]}` : ``
).filter(Boolean);
if (stats.length) {
out += `IVs: ${stats.join(" / ")}
`;
}
}
}
for (let move of set.moves) {
if (move.startsWith(`Hidden Power `) && move.charAt(13) !== "[") {
move = `Hidden Power [${move.slice(13)}]`;
}
out += `- ${move}
`;
}
return out;
}
parseExportedTeamLine(line, isFirstLine, set) {
if (isFirstLine) {
let item;
[line, item] = line.split(" @ ");
if (item) {
set.item = item;
if ((0, import_dex.toID)(set.item) === "noitem")
set.item = "";
}
if (line.endsWith(" (M)")) {
set.gender = "M";
line = line.slice(0, -4);
}
if (line.endsWith(" (F)")) {
set.gender = "F";
line = line.slice(0, -4);
}
if (line.endsWith(")") && line.includes("(")) {
const [name, species] = line.slice(0, -1).split("(");
set.species = import_dex.Dex.species.get(species).name;
set.name = name.trim();
} else {
set.species = import_dex.Dex.species.get(line).name;
set.name = "";
}
} else if (line.startsWith("Trait: ")) {
line = line.slice(7);
set.ability = line;
} else if (line.startsWith("Ability: ")) {
line = line.slice(9);
set.ability = line;
} else if (line === "Shiny: Yes") {
set.shiny = true;
} else if (line.startsWith("Level: ")) {
line = line.slice(7);
set.level = +line;
} else if (line.startsWith("Happiness: ")) {
line = line.slice(11);
set.happiness = +line;
} else if (line.startsWith("Pokeball: ")) {
line = line.slice(10);
set.pokeball = line;
} else if (line.startsWith("Hidden Power: ")) {
line = line.slice(14);
set.hpType = line;
} else if (line.startsWith("Tera Type: ")) {
line = line.slice(11);
set.teraType = line;
} else if (line === "Gigantamax: Yes") {
set.gigantamax = true;
} else if (line.startsWith("EVs: ")) {
line = line.slice(5);
const evLines = line.split("/");
set.evs = { hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0 };
for (const evLine of evLines) {
const [statValue, statName] = evLine.trim().split(" ");
const statid = import_dex.Dex.stats.getID(statName);
if (!statid)
continue;
const value = parseInt(statValue);
set.evs[statid] = value;
}
} else if (line.startsWith("IVs: ")) {
line = line.slice(5);
const ivLines = line.split("/");
set.ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 };
for (const ivLine of ivLines) {
const [statValue, statName] = ivLine.trim().split(" ");
const statid = import_dex.Dex.stats.getID(statName);
if (!statid)
continue;
let value = parseInt(statValue);
if (isNaN(value))
value = 31;
set.ivs[statid] = value;
}
} else if (/^[A-Za-z]+ (N|n)ature/.test(line)) {
let natureIndex = line.indexOf(" Nature");
if (natureIndex === -1)
natureIndex = line.indexOf(" nature");
if (natureIndex === -1)
return;
line = line.substr(0, natureIndex);
if (line !== "undefined")
set.nature = line;
} else if (line.startsWith("-") || line.startsWith("~")) {
line = line.slice(line.charAt(1) === " " ? 2 : 1);
if (line.startsWith("Hidden Power [")) {
const hpType = line.slice(14, -1);
line = "Hidden Power " + hpType;
if (!set.ivs && import_dex.Dex.types.isName(hpType)) {
set.ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 };
const hpIVs = import_dex.Dex.types.get(hpType).HPivs || {};
for (const statid in hpIVs) {
set.ivs[statid] = hpIVs[statid];
}
}
}
if (line === "Frustration" && set.happiness === void 0) {
set.happiness = 0;
}
set.moves.push(line);
}
}
/** Accepts a team in any format (JSON, packed, or exported) */
import(buffer) {
if (buffer.startsWith("[")) {
try {
const team = JSON.parse(buffer);
if (!Array.isArray(team))
throw new Error(`Team should be an Array but isn't`);
for (const set of team) {
set.name = import_dex.Dex.getName(set.name);
set.species = import_dex.Dex.getName(set.species);
set.item = import_dex.Dex.getName(set.item);
set.ability = import_dex.Dex.getName(set.ability);
set.gender = import_dex.Dex.getName(set.gender);
set.nature = import_dex.Dex.getName(set.nature);
const evs = { hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0 };
if (set.evs) {
for (const statid in evs) {
if (typeof set.evs[statid] === "number")
evs[statid] = set.evs[statid];
}
}
set.evs = evs;
const ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 };
if (set.ivs) {
for (const statid in ivs) {
if (typeof set.ivs[statid] === "number")
ivs[statid] = set.ivs[statid];
}
}
set.ivs = ivs;
if (!Array.isArray(set.moves)) {
set.moves = [];
} else {
set.moves = set.moves.map(import_dex.Dex.getName);
}
}
return team;
} catch {
}
}
const lines = buffer.split("\n");
const sets = [];
let curSet = null;
while (lines.length && !lines[0])
lines.shift();
while (lines.length && !lines[lines.length - 1])
lines.pop();
if (lines.length === 1 && lines[0].includes("|")) {
return this.unpack(lines[0]);
}
for (let line of lines) {
line = line.trim();
if (line === "" || line === "---") {
curSet = null;
} else if (line.startsWith("===")) {
} else if (!curSet) {
curSet = {
name: "",
species: "",
item: "",
ability: "",
gender: "",
nature: "",
evs: { hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0 },
ivs: { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 },
level: 100,
moves: []
};
sets.push(curSet);
this.parseExportedTeamLine(line, true, curSet);
} else {
this.parseExportedTeamLine(line, false, curSet);
}
}
return sets;
}
getGenerator(format, seed = null) {
let TeamGenerator;
if ((0, import_dex.toID)(format).includes("gen9computergeneratedteams")) {
TeamGenerator = require(import_dex.Dex.forFormat(format).dataDir + "/cg-teams").default;
} else {
TeamGenerator = require(import_dex.Dex.forFormat(format).dataDir + "/random-teams").default;
}
return new TeamGenerator(format, seed);
}
generate(format, options = null) {
return this.getGenerator(format, options?.seed).getTeam(options);
}
}();
var teams_default = Teams;
//# sourceMappingURL=teams.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../sim/teams.ts"],
"sourcesContent": ["/**\r\n * Teams\r\n * Pokemon Showdown - http://pokemonshowdown.com/\r\n *\r\n * Functions for converting and generating teams.\r\n *\r\n * @license MIT\r\n */\r\n\r\nimport {Dex, toID} from './dex';\r\nimport type {PRNG, PRNGSeed} from './prng';\r\n\r\n/**\r\n * COBBLED: Represents additional move data\r\n */\r\nexport interface AdditionalMoveInfo {\r\n\t/**\r\n\t * COBBLED: The maximum amount of PP the move has.\r\n\t */\r\n\tmaxPp: number;\r\n\t/**\r\n\t * COBBLED: The current amount of PP the move has.\r\n\t */\r\n\tpp: number;\r\n}\r\n\r\nexport interface PokemonSet {\r\n\t/**\r\n\t * Nickname. Should be identical to its base species if not specified\r\n\t * by the player, e.g. \"Minior\".\r\n\t */\r\n\tname: string;\r\n\t/**\r\n\t * Species name (including forme if applicable), e.g. \"Minior-Red\".\r\n\t * This should always be converted to an id before use.\r\n\t */\r\n\tspecies: string;\r\n\t/**\r\n\t * COBBLED: Unique Id for the Pokemon from the mod.\r\n\t */\r\n\tuuid?: string;\r\n\t/**\r\n\t * COBBLED: The current health of the Pokemon being assigned from the mod.\r\n\t */\r\n\tcurrentHealth?: number;\r\n\t/**\r\n\t * COBBLED: The current status of the Pokemon if any from the mod.\r\n\t */\r\n\tstatus?: string;\r\n\tstatusDuration?: number;\r\n\t/**\r\n\t * This can be an id, e.g. \"whiteherb\" or a full name, e.g. \"White Herb\".\r\n\t * This should always be converted to an id before use.\r\n\t */\r\n\titem: string;\r\n\t/**\r\n\t * This can be an id, e.g. \"shieldsdown\" or a full name,\r\n\t * e.g. \"Shields Down\".\r\n\t * This should always be converted to an id before use.\r\n\t */\r\n\tability: string;\r\n\t/**\r\n\t * Each move can be an id, e.g. \"shellsmash\" or a full name,\r\n\t * e.g. \"Shell Smash\"\r\n\t * These should always be converted to ids before use.\r\n\t */\r\n\tmoves: string[];\r\n\t/**\r\n\t * COBBLED: Holds any additional move data coming over from the mod.\r\n\t */\r\n\tmovesInfo?: AdditionalMoveInfo[];\r\n\t/**\r\n\t * This can be an id, e.g. \"adamant\" or a full name, e.g. \"Adamant\".\r\n\t * This should always be converted to an id before use.\r\n\t */\r\n\tnature: string;\r\n\tgender: string;\r\n\t/**\r\n\t * Effort Values, used in stat calculation.\r\n\t * These must be between 0 and 255, inclusive.\r\n\t *\r\n\t * Also used to store AVs for Let's Go\r\n\t */\r\n\tevs: StatsTable;\r\n\t/**\r\n\t * Individual Values, used in stat calculation.\r\n\t * These must be between 0 and 31, inclusive.\r\n\t *\r\n\t * These are also used as DVs, or determinant values, in Gens\r\n\t * 1 and 2, which are represented as even numbers from 0 to 30.\r\n\t *\r\n\t * In Gen 2-6, these must match the Hidden Power type.\r\n\t *\r\n\t * In Gen 7+, Bottle Caps means these can either match the\r\n\t * Hidden Power type or 31.\r\n\t */\r\n\tivs: StatsTable;\r\n\t/**\r\n\t * This is usually between 1 and 100, inclusive,\r\n\t * but the simulator supports levels up to 9999 for testing purposes.\r\n\t */\r\n\tlevel: number;\r\n\t/**\r\n\t * While having no direct competitive effect, certain Pokemon cannot\r\n\t * be legally obtained as shiny, either as a whole or with certain\r\n\t * event-only abilities or moves.\r\n\t */\r\n\tshiny?: boolean;\r\n\t/**\r\n\t * This is technically \"Friendship\", but the community calls this\r\n\t * \"Happiness\".\r\n\t *\r\n\t * It's used to calculate the power of the moves Return and Frustration.\r\n\t * This value must be between 0 and 255, inclusive.\r\n\t */\r\n\thappiness?: number;\r\n\t/**\r\n\t * The pokeball this Pokemon is in. Like shininess, this property\r\n\t * has no direct competitive effects, but has implications for\r\n\t * event legality. For example, any Rayquaza that knows V-Create\r\n\t * must be sent out from a Cherish Ball.\r\n\t *\r\n\t * TODO: actually support this in the validator, switching animations,\r\n\t * and the teambuilder.\r\n\t */\r\n\tpokeball?: string;\r\n\t/**\r\n\t * Hidden Power type. Optional in older gens, but used in Gen 7+\r\n\t * because `ivs` contain post-Battle-Cap values.\r\n\t */\r\n\thpType?: string;\r\n\t/**\r\n\t * Dynamax Level. Affects the amount of HP gained when Dynamaxed.\r\n\t * This value must be between 0 and 10, inclusive.\r\n\t */\r\n\tdynamaxLevel?: number;\r\n\tgigantamax?: boolean;\r\n\t/**\r\n\t * Tera Type\r\n\t */\r\n\tteraType?: string;\r\n}\r\n\r\nexport const Teams = new class Teams {\r\n\tpack(team: PokemonSet[] | null): string {\r\n\t\tif (!team) return '';\r\n\r\n\t\tfunction getIv(ivs: StatsTable, s: keyof StatsTable): string {\r\n\t\t\treturn ivs[s] === 31 || ivs[s] === undefined ? '' : ivs[s].toString();\r\n\t\t}\r\n\r\n\t\tlet buf = '';\r\n\t\tfor (const set of team) {\r\n\t\t\tif (buf) buf += ']';\r\n\r\n\t\t\t// name\r\n\t\t\tbuf += (set.name || set.species);\r\n\r\n\t\t\t// species\r\n\t\t\tconst id = this.packName(set.species || set.name);\r\n\t\t\tbuf += '|' + (this.packName(set.name || set.species) === id ? '' : id);\r\n\r\n\t\t\t// item\r\n\t\t\tbuLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,iBAAwB;AATxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+IO,MAAM,QAAQ,IAAI,MAAMA,OAAM;AAAA,EACpC,KAAK,MAAmC;AACvC,QAAI,CAAC;AAAM,aAAO;AAElB,aAAS,MAAM,KAAiB,GAA6B;AAC5D,aAAO,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,MAAM,SAAY,KAAK,IAAI,CAAC,EAAE,SAAS;AAAA,IACrE;AAEA,QAAI,MAAM;AACV,eAAW,OAAO,MAAM;AACvB,UAAI;AAAK,eAAO;AAGhB,aAAQ,IAAI,QAAQ,IAAI;AAGxB,YAAM,KAAK,KAAK,SAAS,IAAI,WAAW,IAAI,IAAI;AAChD,aAAO,OAAO,KAAK,SAAS,IAAI,QAAQ,IAAI,OAAO,MAAM,KAAK,KAAK;AAGnE,aAAO,MAAM,KAAK,SAAS,IAAI,IAAI;AAGnC,aAAO,MAAM,KAAK,SAAS,IAAI,OAAO;AAGtC,aAAO,MAAM,IAAI,MAAM,IAAI,KAAK,QAAQ,EAAE,KAAK,GAAG;AAGlD,aAAO,OAAO,IAAI,UAAU;AAG5B,UAAI,MAAM;AACV,UAAI,IAAI,KAAK;AACZ,cAAM,OAAO,IAAI,IAAI,IAAI,KAAK,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK;AAAA,MAC1L;AACA,UAAI,QAAQ,UAAU;AACrB,eAA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ropertyDescriptor;
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,YAAY,IAAI,cAAc,KAAK,KAAK,MAAM,OAAO,kBAAiB,cAAc,KAAK,KAAK,CAAC;AAErG,OAAG;AACF,WAAK;AACL,UAAI;AACH,cAAM,OAAO,IAAI,QAAQ,IAAI,KAAK,MAAM,EAAE,aAAa;AAGvD,cAAM,IA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"]
}
+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,QAAQ;AACvB,SAAK,MAAM,CAAC,CAAC,QAAQ;AAErB,SAAK,UAAU,CAAC,CAAC,QAAQ;AAEzB,SAAK,cAAc;AACnB,SAAK,WAAW;AAAA,EACjB;AAAA,EAEA,MAAM,MAAM;AACX,QAAI,QAAQ,CAAC;AAC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;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,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ,QAAQ,CAAC,MAAM,QAAQ,QAAQ,IAAI,IAAI,QAAQ,OAAO,IAAI,iBAAK,QAAQ,IAAI;AAAA,EAChG;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ACb,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;AAC5D,SAAK,YAAY,EAAC,GAAG,QAAO,YAAY,GAAG,QAAQ,UAAS;AAE5D,SAAK,QAAQ,CAAC,CAAC,QAAQ;AACvB,SAAK,SAAS,CAAC,CAAC,QAAQ;AACxB,SAAK,QAAQ,CAAC,CAAC,QAAQ;AACvB,SA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