summaryrefslogtreecommitdiff
path: root/web/src/lib/game/line/statCalculator.ts
blob: 1f7887b4f625d03d01ee8f0f22bc48781f5fe0df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/**
 * Formula evaluation (client port of the reference `StatCalculator`, PORTING.md
 * §8b). The engine keeps its own Dart copy for its internal use; the client
 * needs the same substitution + arithmetic to resolve `%attack% - 1` style
 * lines while rendering ability cards.
 *
 * Substitutes `C` (current character count, clamped to ≥ 2) and `L` (level),
 * then evaluates with the reference parser: integer arithmetic where `/`
 * rounds up (ceil) and `d` rounds down (floor), and `<` / `>` / `=` produce
 * 1 / 0.
 */

export interface FormulaContext {
	/** Current number of characters (clamped to a minimum of 2). */
	characterCount?: number;
	/** Current game level. */
	level?: number;
}

/** The sentinel used past the end of the string (matches no real character). */
const END = '\u0000';

class FormulaParser {
	private pos = -1;
	private ch = END;

	constructor(private readonly str: string) {}

	/** Run the grammar and return the value, or null when unparseable. */
	parse(): number | null {
		try {
			this.nextChar();
			const result = this.parseCondition();
			if (this.pos < this.str.length) return null;
			return result;
		} catch {
			return null;
		}
	}

	private nextChar(): void {
		this.pos += 1;
		this.ch = this.pos < this.str.length ? this.str.charAt(this.pos) : END;
	}

	private eat(charToEat: string): boolean {
		while (this.ch === ' ') this.nextChar();
		if (this.ch === charToEat) {
			this.nextChar();
			return true;
		}
		return false;
	}

	// Grammar (the reference StatCalculator):
	//   condition  = expression | expression (<|>|=) expression
	//   expression = term | expression (+|-) term
	//   term       = factor | term (*|x) factor | term (/) factor | term (d) factor
	//   factor     = +factor | -factor | ( expression ) | number
	//
	// `*` and `x` both multiply; `/` rounds up, `d` rounds down; the
	// comparison operators yield 1 (true) or 0 (false).

	private parseCondition(): number {
		let result = this.parseExpression();
		for (;;) {
			if (this.eat('<')) result = result < this.parseExpression() ? 1 : 0;
			else if (this.eat('>')) result = result > this.parseExpression() ? 1 : 0;
			else if (this.eat('=')) result = result === this.parseExpression() ? 1 : 0;
			else return result;
		}
	}

	private parseExpression(): number {
		let result = this.parseTerm();
		for (;;) {
			if (this.eat('+')) result += this.parseTerm();
			else if (this.eat('-')) result -= this.parseTerm();
			else return result;
		}
	}

	private parseTerm(): number {
		let result = this.parseFactor();
		for (;;) {
			if (this.eat('*')) result *= this.parseFactor();
			else if (this.eat('x')) result *= this.parseFactor();
			else if (this.eat('/')) result = Math.ceil(result / this.parseFactor());
			else if (this.eat('d')) result = Math.floor(result / this.parseFactor());
			else return result;
		}
	}

	private parseFactor(): number {
		if (this.eat('+')) return this.parseFactor();
		if (this.eat('-')) return -this.parseFactor();

		if (this.eat('(')) {
			const result = this.parseExpression();
			if (!this.eat(')')) throw new Error("missing ')'");
			return result;
		}

		const first = this.ch.codePointAt(0) ?? 0;
		if (first >= 48 && first <= 57) {
			const startPos = this.pos;
			while (
				this.ch !== END &&
				this.ch.codePointAt(0)! >= 48 &&
				this.ch.codePointAt(0)! <= 57
			) {
				this.nextChar();
			}
			return parseInt(this.str.substring(startPos, this.pos), 10);
		}

		throw new Error(`unexpected: ${this.ch}`);
	}
}

/** Evaluate a formula string (no C / L substitution). Null when malformed. */
export function evalFormula(str: string): number | null {
	return new FormulaParser(str).parse();
}

/**
 * Substitute C / L from [ctx] (defaulting C=2, L=1) then evaluate. Mirrors the
 * reference `StatCalculator.calculateFormula`; returns null when the result is
 * not an integer.
 */
export function calculateFormula(
	str: string,
	ctx: FormulaContext = {}
): number | null {
	const C = Math.max(2, ctx.characterCount ?? 2);
	const L = ctx.level ?? 1;
	const formula = str.replaceAll('C', String(C)).replaceAll('L', String(L));
	const result = evalFormula(formula);
	return typeof result === 'number' ? result : null;
}