Options
All
  • Public
  • Public/Protected
  • All
Menu

An interface and API for constructing and evaluating dice rolls. The basic structure for a dice roll is a string formula and an object of data against which to parse it.

param formula

The string formula to parse

param data

The data object against which to parse attributes within the formula

example

Attack with advantage

// Construct the Roll instance
let r = new Roll("2d20kh + @prof + @strMod", {prof: 2, strMod: 4});

// The parsed terms of the roll formula
console.log(r.terms); // [Die, OperatorTerm, NumericTerm, OperatorTerm, NumericTerm]

// Execute the roll
await r.evaluate();

// The resulting equation after it was rolled
console.log(r.result); // 16 + 2 + 4

// The total resulting from the roll
console.log(r.total); // 22

Hierarchy

  • Roll

Index

Constructors

  • new Roll(formula: any, data?: {}, options?: {}): Roll
  • Parameters

    • formula: any
    • data: {} = {}
      • options: {} = {}

        Returns Roll

      Properties

      data: any

      The original provided data object which substitutes into attributes of the roll formula

      options: any

      Options which modify or describe the Roll

      terms: RollTerm[]

      The identified terms of the Roll

      _dice: DiceTerm[]

      An array of inner DiceTerms which were evaluated as part of the Roll evaluation

      _formula: string

      Store the original cleaned formula for the Roll, prior to any internal evaluation or simplification

      _evaluated: boolean

      Track whether this Roll instance has been evaluated or not. Once evaluated the Roll is immutable.

      MATH_PROXY: Math = ...

      A Proxy environment for safely evaluating a string using only available Math functions

      CHAT_TEMPLATE: string = "templates/dice/roll.html"

      The HTML template path used to render a complete Roll object to the chat log

      TOOLTIP_TEMPLATE: string = "templates/dice/tooltip.html"

      The HTML template used to render an expanded Roll tooltip to the chat log

      Accessors

      • Return an Array of the individual DiceTerm instances contained within this Roll.

        Returns DiceTerm[]

      • get formula(): string
      • Return a standardized representation for the displayed formula associated with this Roll.

        Returns string

      • get result(): string
      • The resulting arithmetic expression after rolls have been evaluated

        Returns string

      • get total(): number
      • Return the total result of the Roll expression if it has been evaluated.

        Returns number

      • get isDeterministic(): boolean
      • Whether this Roll contains entirely deterministic terms or whether there is some randomness.

        Returns boolean

      • get defaultImplementation(): typeof Roll
      • Get the default configured Roll class.

        Returns typeof Roll

      Methods

      • alter(multiply: number, add: number, [multiplyNumeric]?: boolean): Roll
      • Alter the Roll expression by adding or multiplying the number of dice which are rolled

        Parameters

        • multiply: number

          A factor to multiply. Dice are multiplied before any additions.

        • add: number

          A number of dice to add. Dice are added after multiplication.

        • [multiplyNumeric]: boolean = {}

          Apply multiplication factor to numeric scalar terms

        Returns Roll

        The altered Roll expression

      • Clone the Roll instance, returning a new Roll instance that has not yet been evaluated.

        Returns Roll

      • evaluate([options={}]?: { minimize: boolean; maximize: boolean; async: boolean }): Roll | Promise<Roll>
      • Execute the Roll, replacing dice and evaluating the total result

        example

        Evaluate a Roll expression

        let r = new Roll("2d6 + 4 + 1d4");
        await r.evaluate();
        console.log(r.result); // 5 + 4 + 2
        console.log(r.total); // 11

        Parameters

        • [options={}]: { minimize: boolean; maximize: boolean; async: boolean } = {}

          Options which inform how the Roll is evaluated

          • minimize: boolean
          • maximize: boolean
          • async: boolean

        Returns Roll | Promise<Roll>

        The evaluated Roll instance

      • roll(options?: any): Roll | Promise<Roll>
      • Alias for evaluate.

        see

        {Roll#evaluate}

        Parameters

        • options: any = {}

          Options passed to Roll#evaluate

        Returns Roll | Promise<Roll>

      • reroll(options?: any): Roll
      • Create a new Roll object using the original provided formula and data. Each roll is immutable, so this method returns a new Roll instance using the same data.

        Parameters

        • options: any = {}

        Returns Roll

        A new Roll object, rolled using the same formula and data

      • resetFormula(): string
      • Recompile the formula string that represents this Roll instance from its component terms.

        Returns string

        The re-compiled formula

      • getTooltip(): Promise<string>
      • Render the tooltip HTML for a Roll instance

        Returns Promise<string>

        The rendered HTML tooltip as a string

      • render([options={}]?: { flavor: string; template: string; isPrivate: boolean }): Promise<string>
      • Render a Roll instance to HTML

        Parameters

        • [options={}]: { flavor: string; template: string; isPrivate: boolean } = {}

          Options which affect how the Roll is rendered

          • flavor: string
          • template: string
          • isPrivate: boolean

        Returns Promise<string>

        The rendered HTML template as a string

      • toMessage(messageData?: any, [options]?: options): Promise<any>
      • Transform a Roll instance into a ChatMessage, displaying the roll result. This function can either create the ChatMessage directly, or return the data object that will be used to create.

        Parameters

        • messageData: any = {}

          The data object to use when creating the message

        • [options]: options = {}

          Additional options which modify the created message.

        Returns Promise<any>

        A promise which resolves to the created ChatMessage document if create is true, or the Object of prepared chatData otherwise.

      • toAnchor([options]?: { label: string }): HTMLAnchorElement
      • Construct an inline roll link for this Roll.

        Parameters

        • [options]: { label: string } = {}

          Additional options to configure how the link is constructed.

          • label: string

        Returns HTMLAnchorElement

      • toJSON(): any
      • Represent the data of the Roll as an object suitable for JSON serialization.

        Returns any

        Structured data which can be serialized into JSON

      • _prepareData(data: any): any
      • Prepare the data structure used for the Roll. This is factored out to allow for custom Roll classes to do special data preparation using provided input.

        Parameters

        • data: any

          Provided roll data

        Returns any

        The prepared data object

      • _evaluate([options]?: { minimize: boolean; maximize: boolean }): Promise<Roll>
      • Evaluate the roll asynchronously. A temporary helper method used to migrate behavior from 0.7.x (sync by default) to 0.9.x (async by default).

        Parameters

        • [options]: { minimize: boolean; maximize: boolean } = {}

          Options which inform how evaluation is performed

          • minimize: boolean
          • maximize: boolean

        Returns Promise<Roll>

      • _evaluateSync([options]?: { minimize: boolean; maximize: boolean }): Roll
      • Evaluate the roll synchronously. A temporary helper method used to migrate behavior from 0.7.x (sync by default) to 0.9.x (async by default).

        Parameters

        • [options]: { minimize: boolean; maximize: boolean } = {}

          Options which inform how evaluation is performed

          • minimize: boolean
          • maximize: boolean

        Returns Roll

      • _evaluateTotal(): number
      • Safely evaluate the final total result for the Roll using its component terms.

        Returns number

        The evaluated total

      • create(formula: string, data?: any, options?: any): Roll
      • A factory method which constructs a Roll instance using the default configured Roll class.

        Parameters

        • formula: string

          The formula used to create the Roll instance

        • data: any = {}
        • options: any = {}

        Returns Roll

        The constructed Roll instance

      • Transform an array of RollTerm objects into a cleaned string formula representation.

        Parameters

        • terms: RollTerm[]

          An array of terms to represent as a formula

        Returns string

        The string representation of the formula

      • safeEval(expression: string): number
      • A sandbox-safe evaluation function to execute user-input code with access to scoped Math methods.

        Parameters

        • expression: string

          The input string expression

        Returns number

        The numeric evaluated result

      • After parenthetical and arithmetic terms have been resolved, we need to simplify the remaining expression. Any remaining string terms need to be combined with adjacent non-operators in order to construct parsable terms.

        Parameters

        • terms: RollTerm[]

          An array of terms which is eligible for simplification

        Returns RollTerm[]

        An array of simplified terms

      • simulate(formula: string, n?: number): Promise<number[]>
      • Simulate a roll and evaluate the distribution of returned results

        Parameters

        • formula: string

          The Roll expression to simulate

        • n: number = 10000

          The number of simulations

        Returns Promise<number[]>

        The rolled totals

      • parse(formula: string, data: any): RollTerm[]
      • Parse a formula by following an order of operations:

        Step 1: Replace formula data Step 2: Split outer-most parenthetical groups Step 3: Further split outer-most dice pool groups Step 4: Further split string terms on arithmetic operators Step 5: Classify all remaining strings

        Parameters

        • formula: string

          The original string expression to parse

        • data: any

          A data object used to substitute for attributes in the formula

        Returns RollTerm[]

        A parsed array of RollTerm instances

      • replaceFormulaData(formula: string, data: any, [options]?: { missing: string; warn: boolean }): string
      • Replace referenced data attributes in the roll formula with values from the provided data. Data references in the formula use the @attr syntax and would reference the corresponding attr key.

        static

        Parameters

        • formula: string

          The original formula within which to replace

        • data: any

          The data object which provides replacements

        • [options]: { missing: string; warn: boolean } = {}

          Options which modify formula replacement

          • missing: string
          • warn: boolean

        Returns string

      • validate(formula: string): boolean
      • Validate that a provided roll formula can represent a valid

        Parameters

        • formula: string

          A candidate formula to validate

        Returns boolean

        Is the provided input a valid dice formula?

      • _classifyStringTerm(term: string, [options={}]?: { intermediate: boolean; prior: string | RollTerm; next: string | RollTerm }): RollTerm
      • Classify a remaining string term into a recognized RollTerm class

        internal

        Parameters

        • term: string

          A remaining un-classified string

        • [options={}]: { intermediate: boolean; prior: string | RollTerm; next: string | RollTerm } = {}

          Options which customize classification

        Returns RollTerm

        A classified RollTerm instance

      • expandInlineResult(a: HTMLAnchorElement): Promise<void>
      • Expand an inline roll element to display its contained dice result as a tooltip.

        Parameters

        • a: HTMLAnchorElement

          The inline-roll button

        Returns Promise<void>

      • collapseInlineResult(a: HTMLAnchorElement): void
      • Collapse an expanded inline roll to conceal its tooltip.

        Parameters

        • a: HTMLAnchorElement

          The inline-roll button

        Returns void

      • fromData(data: any): Roll
      • Recreate a Roll instance using a provided data object

        Parameters

        • data: any

          Unpacked data representing the Roll

        Returns Roll

        A reconstructed Roll instance

      • fromJSON(json: string): Roll
      • Recreate a Roll instance using a provided JSON string

        Parameters

        • json: string

          Serialized JSON data representing the Roll

        Returns Roll

        A reconstructed Roll instance

      • Manually construct a Roll object by providing an explicit set of input terms

        example

        Construct a Roll instance from an array of component terms

        const t1 = new Die({number: 4, faces: 8};
        const plus = new OperatorTerm({operator: "+"});
        const t2 = new NumericTerm({number: 8});
        const roll = Roll.fromTerms([t1, plus, t2]);
        roll.formula; // 4d8 + 8

        Parameters

        • terms: RollTerm[]

          The array of terms to use as the basis for the Roll

        • options: any = {}

        Returns Roll

        The constructed Roll instance

      • _splitParentheses(_formula: string): string[]
      • Split a formula by identifying its outer-most parenthetical and math terms

        Parameters

        • _formula: string

          The raw formula to split

        Returns string[]

        An array of terms, split on parenthetical terms

      • _splitMathArgs(expression: string): MathTerm[]
      • Handle closing of a parenthetical term to create a MathTerm expression with a function and arguments

        Parameters

        • expression: string

          The expression to split

        Returns MathTerm[]

        An array of evaluated MathTerm instances

      • _splitPools(_formula: string): string[]
      • Split a formula by identifying its outermost dice pool terms.

        Parameters

        • _formula: string

          The raw formula to split

        Returns string[]

        An array of terms, split on parenthetical terms

      • _splitGroup(_formula: string, options?: { openRegexp: RegExp; closeRegexp: RegExp; openSymbol: string; closeSymbol: string; onClose: Function }): string[]
      • Split a formula by identifying its outermost groups using a certain group symbol like parentheses or brackets.

        Parameters

        • _formula: string

          The raw formula to split

        • options: { openRegexp: RegExp; closeRegexp: RegExp; openSymbol: string; closeSymbol: string; onClose: Function } = {}

          Options that configure how groups are split

          • openRegexp: RegExp
          • closeRegexp: RegExp
          • openSymbol: string
          • closeSymbol: string
          • onClose: Function

        Returns string[]

        An array of terms, split on dice pool terms

      • _splitOperators(_formula: string): (string | OperatorTerm)[]
      • Split a formula by identifying arithmetic terms

        Parameters

        • _formula: string

          The raw formula to split

        Returns (string | OperatorTerm)[]

        An array of terms, split on arithmetic operators

      • _extractFlavors(formula: string): { formula: string; flavors: any }
      • Temporarily remove flavor text from a string formula allowing it to be accurately parsed.

        Parameters

        • formula: string

          The formula to extract

        Returns { formula: string; flavors: any }

        The cleaned formula and extracted flavor mapping

        • formula: string
        • flavors: any
      • _restoreFlavor(term: string, flavors: any): string
      • Restore flavor text to a string term

        Parameters

        • term: string

          The string term possibly containing flavor symbols

        • flavors: any

          The extracted flavors object

        Returns string

        The restored term containing flavor text