summaryrefslogtreecommitdiff
path: root/web/src/lib/game/line/statApplier.ts
diff options
context:
space:
mode:
Diffstat (limited to 'web/src/lib/game/line/statApplier.ts')
-rw-r--r--web/src/lib/game/line/statApplier.ts350
1 files changed, 350 insertions, 0 deletions
diff --git a/web/src/lib/game/line/statApplier.ts b/web/src/lib/game/line/statApplier.ts
new file mode 100644
index 0000000..1ce05dd
--- /dev/null
+++ b/web/src/lib/game/line/statApplier.ts
@@ -0,0 +1,350 @@
+/**
+ * Monster-stat substitution (client port of the reference `StatApplier`,
+ * PORTING.md §8b). Resolves `%attack% - 1` style lines against a monster's
+ * actual stats, producing the display strings the ability-card lines need:
+ * a normal value, an elite value (prefixed `!£` when both are shown), and any
+ * leftover line text (prefixed `!`). Stand-alone formulas (e.g. `C+L`) are
+ * evaluated in place.
+ *
+ * The engine keeps its own Dart copy; the client needs it to render ability
+ * cards faithfully. It operates on the monster's level stats (from `/data/`)
+ * and the standee types present, not on live state.
+ */
+
+import { calculateFormula } from './statCalculator';
+
+/** MonsterType index: 0 normal, 1 elite, 2 boss, 3 summon. */
+export type MonsterType = 0 | 1 | 2 | 3;
+const ELITE: MonsterType = 1;
+
+/** One stat block (`normal` / `elite` / a boss level's inline stats). */
+export interface StatBlock {
+ health?: number | string;
+ move?: number | string;
+ attack?: number | string;
+ range?: number;
+ attributes?: string[];
+}
+
+/** The monster's stats for its current level (already level-resolved). */
+export interface StatLevel {
+ normal?: StatBlock;
+ elite?: StatBlock;
+ /** Present when the level is a boss (its stats live inline on the level). */
+ boss?: StatBlock;
+}
+
+/** The data the applier needs about a monster. */
+export interface StatMonster {
+ level: StatLevel;
+ /** The `MonsterType` of each standee present. */
+ standeeTypes: MonsterType[];
+ /** Whether the monster row is the active one. */
+ isActive: boolean;
+}
+
+/** Formula + display context. */
+export interface StatApplierContext {
+ characterCount?: number;
+ level?: number;
+ /** The "no standees" setting (shows both stats when the monster is active). */
+ noStandees?: boolean;
+}
+
+/** Resolve a stat to a number, or null when a formula cannot be evaluated. */
+function calcStat(value: number | string | undefined, ctx: StatApplierContext): number | null {
+ if (value == null) return null;
+ if (typeof value === 'number') return value;
+ return calculateFormula(value, ctx);
+}
+
+/** The single characters the formula scanner treats as formula content. */
+const numberish = (ch: string): boolean => /^[\d ()xCL/*+-]+$/.test(ch);
+
+/** Pull the `{token: nr}` pairs out of a stat block's display attributes. */
+function parseTokens(attributes: string[] | undefined, ctx: StatApplierContext): Record<string, number> {
+ const map: Record<string, number> = {};
+ for (let item of attributes ?? []) {
+ const sizeMod = item.charAt(0);
+ if (sizeMod === '^' || (sizeMod === '*' && item.length > 1)) {
+ item = item.substring(1);
+ }
+ if (item.charAt(0) === '%') {
+ for (let i = 1; i < item.length; i++) {
+ if (item.charAt(i) === '%') {
+ const token = item.substring(1, i);
+ let number = 0;
+ if (i !== item.length - 1) {
+ for (let j = i + 2; j < item.length; j++) {
+ if (item.charAt(j) === ' ' || j === item.length - 1) {
+ const nr = item.substring(i + 1, j + 1);
+ const res = calculateFormula(nr, ctx);
+ if (res != null) number = res;
+ break;
+ }
+ }
+ }
+ if (token === 'target' && number === 0) continue;
+ map[token] = number;
+ break; // only one token per attribute line
+ }
+ }
+ }
+ }
+ return map;
+}
+
+/** The token values for the monster's normal or elite stats. */
+function getStatTokens(
+ monster: StatMonster,
+ isElite: boolean,
+ ctx: StatApplierContext
+): Record<string, number> {
+ const { normal, elite, boss } = monster.level;
+ if (boss != null) {
+ if (isElite) return {};
+ return parseTokens(boss.attributes, ctx);
+ }
+ const data = isElite ? elite : normal;
+ if (data == null) return {};
+ return parseTokens(data.attributes, ctx);
+}
+
+/** The condition tokens appended after an attack line (all but the stats). */
+const nonConditionStat = (item: string): boolean =>
+ /[a-z]/.test(item) &&
+ item !== 'shield' &&
+ item !== 'retaliate' &&
+ item !== 'range' &&
+ item !== 'heal' &&
+ item !== 'jump';
+
+function applyStatForToken(
+ formula: string,
+ line: string,
+ sizeModifier: string,
+ startIndex: number,
+ endIndex: number,
+ monster: StatMonster,
+ showNormal: boolean,
+ showElite: boolean,
+ lastToken: string,
+ normalTokens: Record<string, number>,
+ eliteTokens: Record<string, number>,
+ ctx: StatApplierContext
+): string[] {
+ if (!showElite && !showNormal) return [line];
+
+ const retVal: string[] = [];
+ const tokens: string[] = [];
+ const eTokens: string[] = [];
+ let normalValue = 0;
+ let eliteValue = 0;
+ let skipCalculation = false;
+ const normalBlock = monster.level.boss ?? monster.level.normal;
+ const eliteBlock = monster.level.elite;
+
+ if (lastToken === 'attack') {
+ if (normalBlock == null) return [];
+ const calc = calcStat(normalBlock.attack, ctx);
+ if (calc != null) normalValue = calc;
+ else skipCalculation = true;
+ if (eliteBlock != null) {
+ const ec = calcStat(eliteBlock.attack, ctx);
+ if (ec != null) eliteValue = ec;
+ }
+ for (const item of Object.keys(normalTokens)) {
+ if (nonConditionStat(item)) tokens.push(`%${item}%`);
+ }
+ for (const item of Object.keys(eliteTokens)) {
+ if (nonConditionStat(item)) eTokens.push(`%${item}%`);
+ }
+ } else if (lastToken === 'range') {
+ if ((normalBlock?.range ?? 0) !== 0) {
+ normalValue = normalBlock?.range ?? 0;
+ if (eliteBlock != null) eliteValue = eliteBlock.range ?? 0;
+ }
+ } else if (lastToken === 'move') {
+ normalValue = calcStat(normalBlock?.move, ctx) ?? 0;
+ if (eliteBlock != null) eliteValue = calcStat(eliteBlock.move, ctx) ?? 0;
+ } else if (lastToken === 'shield') {
+ if (eliteBlock != null && eliteTokens.shield != null) eliteValue = eliteTokens.shield;
+ if (normalBlock != null && normalTokens.shield != null) normalValue = normalTokens.shield;
+ } else if (lastToken === 'retaliate') {
+ if (eliteBlock != null && eliteTokens.retaliate != null) eliteValue = eliteTokens.retaliate;
+ if (normalBlock != null && normalTokens.retaliate != null)
+ normalValue = normalTokens.retaliate;
+ }
+
+ let normalResult = formula;
+ if (!skipCalculation) {
+ const res = calculateFormula(`${formula}+${normalValue}`, ctx);
+ if (res != null) normalResult = (res < 0 ? 0 : res).toString();
+ else skipCalculation = true;
+ }
+
+ let newStartOfLine = line.substring(0, startIndex);
+ if (showNormal) {
+ newStartOfLine += normalResult;
+ if (!skipCalculation) {
+ for (const item of tokens) {
+ newStartOfLine += `|${item}`;
+ const key = item.substring(1, item.length - 1);
+ const value = normalTokens[key] ?? 0;
+ if (value > 0) newStartOfLine += String(value);
+ }
+ }
+ }
+
+ // Special case: uncalculable and only elites ("heed the pigs").
+ if (eliteBlock != null && skipCalculation && showElite && !showNormal) {
+ newStartOfLine += normalResult;
+ }
+
+ if (eliteBlock != null && !skipCalculation && showElite) {
+ if (showNormal) newStartOfLine += '/';
+ retVal.push(newStartOfLine);
+ const eliteResult =
+ calculateFormula(`${formula}+${eliteValue}`, ctx) ?? 0;
+ const clamped = eliteResult < 0 ? 0 : eliteResult;
+ let eliteString = `!${sizeModifier}£${clamped}`;
+ for (const item of eTokens) {
+ eliteString += `|${item}`;
+ const key = item.substring(1, item.length - 1);
+ const value = eliteTokens[key]!;
+ if (value > 0) eliteString += String(value);
+ }
+ retVal.push(eliteString);
+ } else {
+ retVal.push(newStartOfLine);
+ }
+
+ if (endIndex < line.length) {
+ const leftOver = `!${sizeModifier}${line.substring(endIndex + 1, line.length)}`;
+ retVal.push(leftOver);
+ }
+ return retVal;
+}
+
+/**
+ * Apply the monster's stats to a line. Returns the list of display strings
+ * (usually one; more when an elite/normal split or trailing text is produced).
+ */
+export function applyMonsterStats(
+ lineInput: string,
+ sizeToken: string,
+ monster: StatMonster,
+ forceShowAll: boolean,
+ ctx: StatApplierContext = {}
+): string[] {
+ let showElite = false;
+ const noStandees = ctx.noStandees ?? false;
+ if ((noStandees && monster.isActive) || monster.standeeTypes.includes(ELITE)) {
+ showElite = true;
+ }
+ let showNormal = false;
+ if (
+ (noStandees && monster.isActive) ||
+ monster.standeeTypes.some((t) => t !== ELITE)
+ ) {
+ showNormal = true;
+ }
+ if (forceShowAll) {
+ showElite = true;
+ showNormal = true;
+ }
+
+ let line = lineInput;
+ let retVal: string[] = [];
+
+ const normalTokens = getStatTokens(monster, false, ctx);
+ const eliteTokens = getStatTokens(monster, true, ctx);
+
+ let lastToken = '';
+ let isInToken = false;
+ let tokenStartIndex = 0;
+
+ for (let i = 0; i < line.length; i++) {
+ if (line.charAt(i) === '%') {
+ if (!isInToken) {
+ isInToken = true;
+ tokenStartIndex = i + 1;
+ } else {
+ isInToken = false;
+ lastToken = line.substring(tokenStartIndex, i);
+ }
+ }
+
+ const isStart =
+ (!isInToken &&
+ (line.charAt(i) === '+' ||
+ line.charAt(i) === '-' ||
+ line.charAt(i) === 'C' ||
+ line.charAt(i) === 'L')) ||
+ line.charAt(i) === 'X' ||
+ ((numberish(line.charAt(i)) && lastToken === '') &&
+ (i === 0 || line.charAt(i - 1) === ' '));
+
+ if (isStart) {
+ let formula = line.charAt(i);
+ const startIndex = i;
+ let endIndex = i;
+
+ for (let j = i + 1; j < lineInput.length; j++) {
+ const val = lineInput.charAt(j);
+ if (numberish(val) || val === 'd') {
+ if (val !== ' ') formula += val;
+ endIndex = j;
+ } else {
+ i = j;
+ if (lineInput.charAt(i - 1) === ' ') {
+ i = j - 1;
+ endIndex -= 1;
+ }
+ if (i > 0 && lineInput.charAt(i - 1) === '(') {
+ i = j - 1;
+ endIndex -= 1;
+ formula = formula.substring(0, formula.length - 1);
+ if (i > 1 && lineInput.charAt(i - 2) === ' ') {
+ i = j - 1;
+ endIndex -= 1;
+ }
+ }
+ break;
+ }
+ }
+
+ if (
+ (formula.length > 1 && lastToken !== '') ||
+ formula.length > 2
+ ) {
+ if (lastToken !== '') {
+ retVal = applyStatForToken(
+ formula,
+ line,
+ sizeToken,
+ startIndex,
+ endIndex,
+ monster,
+ showNormal,
+ showElite,
+ lastToken,
+ normalTokens,
+ eliteTokens,
+ ctx
+ );
+ lastToken = '';
+ if (retVal.length > 0) return retVal;
+ } else {
+ const result = calculateFormula(formula, ctx);
+ if (result != null) {
+ const r = result < 0 ? 0 : result;
+ line = line.slice(0, startIndex) + String(r) + line.slice(endIndex + 1);
+ }
+ }
+ }
+ }
+ }
+
+ return [line];
+}