8000 fix(combat): accept compound dice notation like "1d6+4+2d6" by Mnehmos · Pull Request #51 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 78 additions & 33 deletions src/engine/combat/rng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,22 @@ export class CombatRNG {
}

/**
* Parse and execute standard dice notation (NdS+M or NdS-M)
* Examples: "1d20", "2d6+3", "1d8-1"
* Parse and execute standard dice notation, including multi-term sums.
* Examples: "1d20", "2d6+3", "1d8-1", "1d6+4+2d6" (sneak attack), "1d8+3+2d8" (smite)
*/
roll(notation: string): number {
const match = notation.match(/^(\d+)d(\d+)(([+\-])(\d+))?$/i);
if (!match) {
throw new Error(`Invalid dice notation: ${notation}`);
}

const count = parseInt(match[1], 10);
const sides = parseInt(match[2], 10);
const modifier = match[3] ? parseInt(match[4] + match[5], 10) : 0;

const terms = parseDiceTerms(notation);
let total = 0;
for (let i = 0; i < count; i++) {
total += this.rollDie(sides);
for (const term of terms) {
if (term.kind === 'dice') {
for (let i = 0; i < term.count; i++) {
total += term.sign * this.rollDie(term.sides);
}
} else {
total += term.sign * term.value;
}
}

return total + modifier;
return total;
}

/**
Expand Down Expand Up @@ -276,34 +273,33 @@ export class CombatRNG {
}

/**
* Roll damage dice with detailed breakdown
* Roll damage dice with detailed breakdown.
* Supports compound expressions like "1d6+4+2d6" (sneak attack) and "1d8+3+2d8" (smite).
*/
rollDamageDetailed(notation: string): DamageResult {
const match = notation.match(/^(\d+)d(\d+)(([+\-])(\d+))?$/i);
if (!match) {
throw new Error(`Invalid dice notation: ${notation}`);
}

const count = parseInt(match[1], 10);
const sides = parseInt(match[2], 10);
const modifierSign = match[4] || '+';
const modifierValue = match[5] ? parseInt(match[5], 10) : 0;
const modifier = modifierSign === '-' ? -modifierValue : modifierValue;

const terms = parseDiceTerms(notation);
const rolls: number[] = [];
for (let i = 0; i < count; i++) {
rolls.push(this.rollDie(sides));
let diceTotal = 0;
let modifier = 0;

for (const term of terms) {
if (term.kind === 'dice') {
for (let i = 0; i < term.count; i++) {
const r = this.rollDie(term.sides);
rolls.push(term.sign * r);
diceTotal += term.sign * r;
}
} else {
modifier += term.sign * term.value;
}
}

const diceTotal = rolls.reduce((sum, r) => sum + r, 0);
const total = diceTotal + modifier;

return {
notation,
rolls,
diceTotal,
modifier,
total
total: diceTotal + modifier
};
}
}
Expand Down Expand Up @@ -334,3 +330,52 @@ export interface DamageResult {
modifier: number; // Flat modifier
total: number; // Final damage total
}

type DiceTerm =
| { kind: 'dice'; count: number; sides: number; sign: 1 | -1 }
| { kind: 'scalar'; value: number; sign: 1 | -1 };

/**
* Pars 10BC8 e compound dice notation into a list of terms.
* Accepts a `+`/`-`-joined chain of dice (`NdS`, `dS`) and integers.
* Examples: `1d6+4+2d6`, `1d8+3+2d8`, `2d6+1d4-2`, `d20+5`.
*
* Strict grammar — rejects malformed operator chains like `1d6++2`,
* `1d6--2`, `1d6+`, or trailing operators. Pattern:
* <term> ( [+-] <term> )*
* <term> := <int> | <int>?d<int>
* with at most one leading sign.
*/
export function parseDiceTerms(notation: string): DiceTerm[] {
const stripped = notation.replace(/\s+/g, '');
if (!stripped) {
throw new Error(`Invalid dice notation: ${notation}`);
}
const TERM = String.raw`(?:\d*d\d+|\d+)`;
const STRICT = new RegExp(`^[+-]?${TERM}(?:[+-]${TERM})*$`, 'i');
if (!STRICT.test(stripped)) {
throw new Error(`Invalid dice notation: ${notation}`);
}

// Tokenize once the grammar check has passed.
const tokens = stripped.match(/[+-]?[^+-]+/g)!;

const terms: DiceTerm[] = [];
for (const raw of tokens) {
const sign: 1 | -1 = raw.startsWith('-') ? -1 : 1;
const body = raw.replace(/^[+-]/, '');
const diceMatch = body.match(/^(\d*)d(\d+)$/i);
if (diceMatch) {
const count = diceMatch[1] === '' ? 1 : parseInt(diceMatch[1], 10);
const sides = parseInt(diceMatch[2], 10);
if (count <= 0 || sides <= 0) {
throw new Error(`Invalid dice notation: ${notation}`);
}
terms.push({ kind: 'dice', count, sides, sign });
continue;
}
// Grammar already guaranteed scalar shape.
terms.push({ kind: 'scalar', value: parseInt(body, 10), sign });
}
return terms;
}
59 changes: 59 additions & 0 deletions tests/combat/rng.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,65 @@ describe('CombatRNG', () => {
expect(() => rng.roll('invalid')).toThrow('Invalid dice notation');
expect(() => rng.roll('2x6')).toThrow('Invalid dice notation');
});

it('should parse compound sneak-attack expression (1d6+4+2d6)', () => {
const rng = new CombatRNG('compound-sa');
const result = rng.roll('1d6+4+2d6');
// min: 1 + 4 + 2 = 7; max: 6 + 4 + 12 = 22
expect(result).toBeGreaterThanOrEqual(7);
expect(result).toBeLessThanOrEqual(22);
});

it('should parse compound smite expression (1d8+3+2d8)', () => {
const rng = new CombatRNG('compound-smite');
const result = rng.roll('1d8+3+2d8');
// min: 1 + 3 + 2 = 6; max: 8 + 3 + 16 = 27
expect(result).toBeGreaterThanOrEqual(6);
expect(result).toBeLessThanOrEqual(27);
});

it('should parse mixed dice with subtraction (2d6+1d4-2)', () => {
const rng = new CombatRNG('compound-mixed');
const result = rng.roll('2d6+1d4-2');
// min: 2 + 1 - 2 = 1; max: 12 + 4 - 2 = 14
expect(result).toBeGreaterThanOrEqual(1);
expect(result).toBeLessThanOrEqual(14);
});

it('should parse shorthand single die (d20)', () => {
const rng = new CombatRNG('shorthand-d20');
const result = rng.roll('d20');
expect(result).toBeGreaterThanOrEqual(1);
expect(result).toBeLessThanOrEqual(20);
});

it('rollDamageDetailed returns separate dice and modifier for compound notation', () => {
const rng = new CombatRNG('compound-detail');
const detail = rng.rollDamageDetailed('1d6+4+2d6');
expect(detail.notation).toBe('1d6+4+2d6');
// 1 + 2 = 3 dice rolled; modifier = 4
expect(detail.rolls).toHaveLength(3);
expect(detail.modifier).toBe(4);
expect(detail.total).toBe(detail.diceTotal + detail.modifier);
});

// Strict-grammar regression: malformed operator sequences must throw
// rather than silently evaluate (caught by reviewers on PR #51).
it.each([
'1d6++2',
'1d6--2',
' 6C83 1d6+-2',
'1d6-+2',
'1d6+',
'1d6-',
'+',
'++1d6',
'1d6+2+',
'1d6 + + 2'
])('rejects malformed operator sequence: %s', (notation) => {
const rng = new CombatRNG('malformed-ops');
expect(() => rng.roll(notation)).toThrow('Invalid dice notation');
});
});

describe('Advantage/Disadvantage', () => {
Expand Down
Loading
0