holy-heck-i-really-like-stats/calc.js

304 lines
7.6 KiB
JavaScript
Raw Normal View History

import {
2023-04-26 17:01:02 +10:00
calculate,
2023-04-27 11:17:22 +10:00
toID,
2023-04-26 17:01:02 +10:00
Field,
Generations,
2023-04-26 17:01:02 +10:00
Move,
Pokemon,
Result,
2023-04-27 09:45:47 +10:00
} from "@ajhyndman/smogon-calc";
2023-04-26 17:01:02 +10:00
import assert from "assert";
import { createToken, Lexer } from "chevrotain";
2023-04-26 17:01:02 +10:00
2023-04-27 09:51:37 +10:00
const gen = Generations.get(9);
2023-04-26 17:01:02 +10:00
/**
* Creates a lexer.
*
* @returns {Lexer}
*/
function buildLexer() {
const Boost = createToken({ name: "Boost", pattern: /[+-]\d+/ });
const EV = createToken({ name: "EV", pattern: /\d+[+-]?/ });
const Stat = createToken({
2023-04-26 17:01:02 +10:00
name: "Stat",
pattern: /HP|Atk|Def|SpA|SpD|Spe/,
});
const Item = createToken({
2023-04-26 17:01:02 +10:00
name: "Item",
pattern: new RegExp([...gen.items].map((i) => i.name).join("|")),
2023-04-26 17:01:02 +10:00
});
const Ability = createToken({
2023-04-26 17:01:02 +10:00
name: "Ability",
pattern: new RegExp([...gen.abilities].map((a) => a.name).join("|")),
2023-04-26 17:01:02 +10:00
});
const Pokemon = createToken({
2023-04-26 17:01:02 +10:00
name: "Pokemon",
pattern: new RegExp([...gen.species].map((s) => s.name).join("|")),
2023-04-26 17:01:02 +10:00
});
const Move = createToken({
2023-04-26 17:01:02 +10:00
name: "Move",
pattern: new RegExp([...gen.moves].map((m) => m.name).join("|")),
2023-04-26 17:01:02 +10:00
});
const whitespace = createToken({
2023-04-26 17:01:02 +10:00
name: "Whitespace",
pattern: /\s+/,
group: Lexer.SKIPPED,
});
const div = createToken({
2023-04-26 17:01:02 +10:00
name: "div",
pattern: "/",
group: Lexer.SKIPPED,
});
const vs = createToken({
2023-04-26 17:01:02 +10:00
name: "vs",
2023-04-26 17:14:42 +10:00
pattern: /vs\.?/,
2023-04-26 17:01:02 +10:00
});
const terrainEnter = createToken({
2023-04-26 17:01:02 +10:00
name: "terrainEnter",
pattern: "in",
push_mode: "terrain_mode",
});
const Weather = createToken({
2023-04-26 17:01:02 +10:00
name: "Weather",
pattern: /Sun|Rain|Sand|Snow/,
});
const Terrain = createToken({
2023-04-26 17:01:02 +10:00
name: "Terrain",
pattern: /(Electric|Grassy|Misty|Psychic) Terrain/,
});
const screenEnter = createToken({
2023-04-26 17:01:02 +10:00
name: "screenEnter",
pattern: "through",
push_mode: "screen_mode",
});
return new Lexer({
modes: {
default_mode: [
whitespace,
div,
vs,
Boost,
EV,
Stat,
Item,
Ability,
Pokemon,
Move,
terrainEnter,
screenEnter,
],
terrain_mode: [whitespace, screenEnter, Weather, Terrain],
screen_mode: [whitespace, Move],
},
defaultMode: "default_mode",
});
}
/**
* @generator
* @template T item type
* @param {T[]} arr
* @yields {T} item
*/
function* iterate(arr) {
for (const a of arr) {
yield a;
}
}
/**
* @param {string} type token type
* @param {import("chevrotain").IToken} token token
2023-04-26 17:01:02 +10:00
* @return {string} matched token
*/
function unwrapToken(type, token) {
assert(
token.tokenType.name == type,
2023-04-27 11:23:48 +10:00
`expected token ${type}, got ${token.tokenType.name}`
2023-04-26 17:01:02 +10:00
);
return token.image;
}
const POS_NATURES = {
atk: "Adamant",
def: "Bold",
spa: "Modest",
spd: "Calm",
spe: "Jolly",
};
const NEG_NATURES = {
atk: "Modest",
def: "Lonely",
spa: "Adamant",
spd: "Rash",
spe: "Brave",
};
/**
* Parses a Smogon calculator output:
*
* -2 8 SpA Choice Specs Torkoal vs.
* 252 HP / 4+ SpD Assault Vest Abomasnow
* in Sun
* through Light Screen
*
* @param {string} line textual line
* @return {Result} calculation result
2023-04-26 17:01:02 +10:00
*/
function parseAndCalculate(line) {
const lexer = buildLexer();
const result = lexer.tokenize(line);
if (result.errors && result.errors.length > 0) {
console.error("Unparsed tokens: %o", result.errors);
}
/** @type {string} */
var attacker;
/** @type {string} */
var defender;
/** @type {import("@ajhyndman/smogon-calc").State.Pokemon} */
2023-04-26 17:01:02 +10:00
var attackerOpts = {};
/** @type {import("@ajhyndman/smogon-calc").State.Pokemon} */
2023-04-26 17:01:02 +10:00
var defenderOpts = {};
/** @type {string} */
var move;
/** @type {import("@ajhyndman/smogon-calc").State.Field} */
2023-04-26 17:01:02 +10:00
var field = {};
// Tokenising state.
var isAttacker = true;
var it = iterate(result.tokens);
const opts = () => (isAttacker ? attackerOpts : defenderOpts);
while (true) {
let item = it.next().value;
if (!item) break;
switch (item.tokenType.name) {
case "Boost":
{
let boost = unwrapToken("Boost", item);
let ev = unwrapToken("EV", it.next().value);
let stat = unwrapToken("Stat", it.next().value).toLowerCase();
opts().boosts = { [stat]: parseInt(boost), ...opts().boosts };
opts().evs = { [stat]: parseInt(ev), ...opts().evs };
if (ev.endsWith("+")) {
opts().nature = POS_NATURES[stat];
} else if (ev.endsWith("-")) {
opts().nature = NEG_NATURES[stat];
}
}
break;
case "EV":
{
let ev = unwrapToken("EV", item);
let stat = unwrapToken("Stat", it.next().value).toLowerCase();
opts().evs = { [stat]: parseInt(ev), ...opts().evs };
if (ev.endsWith("+")) {
opts().nature = POS_NATURES[stat];
} else if (ev.endsWith("-")) {
opts().nature = NEG_NATURES[stat];
}
}
break;
case "Stat":
throw Error("Impossible state: bare Stat");
2023-04-26 17:01:02 +10:00
case "Item":
opts().item = unwrapToken("Item", item);
break;
case "Pokemon":
{
let name = unwrapToken("Pokemon", item);
if (isAttacker) attacker = name;
else defender = name;
}
break;
case "Move":
move = unwrapToken("Move", item);
break;
case "terrainEnter":
{
let next = it.next().value;
switch (next.tokenType.name) {
case "Weather":
field.weather = next.image;
break;
case "Terrain":
field.terrain = next.image;
break;
default:
throw Error(
"Unhandled terrain %s: %s",
next.tokenType.name,
next.image
);
}
}
break;
case "screenEnter":
{
let screen = unwrapToken("Move", it.next().value);
field.defenderSide = field.defenderSide || {};
field.defenderSide.isLightScreen = screen === "Light Screen";
field.defenderSide.isReflect = screen === "Reflect";
field.defenderSide.isAuroraVeil = screen === "Aurora Veil";
field.defenderSide.is;
}
break;
case "vs":
isAttacker = false;
break;
default:
console.error("unmatched token type: %s", item.tokenType.name);
break;
}
}
2023-04-27 09:51:42 +10:00
// Pre-checking before the calculator throws unreadable errors.
2023-04-27 11:17:22 +10:00
if (!gen.species.get(toID(attacker)))
throw Error(`No species named ${attacker}`);
2023-04-27 11:17:22 +10:00
if (!gen.species.get(toID(defender)))
throw Error(`No species named ${defender}`);
2023-04-27 11:17:22 +10:00
if (!gen.moves.get(toID(move))) throw Error(`No move named ${move}`);
2023-04-27 09:51:42 +10:00
2023-04-26 17:01:02 +10:00
return calculate(
gen,
new Pokemon(gen, attacker, attackerOpts),
new Pokemon(gen, defender, defenderOpts),
new Move(gen, move),
new Field(field)
);
}
function test() {
const text =
"-2 8 SpA Choice Specs Torkoal Overheat vs. 252 HP / 4+ SpD Assault Vest Abomasnow in Sun through Light Screen";
const res = parseAndCalculate(text);
assert(res.attacker.boosts.spa === -2, "should have -2 SpA");
assert(res.attacker.evs.spa === 8, "should have 8 SpA EVs");
assert(res.attacker.item === "Choice Specs", "should have Choice Specs");
assert(res.attacker.name === "Torkoal", "should be Torkoal");
assert(res.move.name === "Overheat", "should be Overheat");
assert(res.defender.evs.hp === 252, "should have 252 HP EVs");
assert(res.defender.evs.spd === 4, "should have 4 SpD EVs");
assert(res.field.weather === "Sun", "should be in sun");
assert(
res.desc().replace(/:.*/, "") === text,
"non-damage text should be equivalent to input"
);
}
export { parseAndCalculate, test };