< Dice‎ | AST‎ | DiceAST

DiceAST.Evaluate Method (RollData, DiceAST, Int32)

From DiceRoller Documentation

Evaluates the node, causing it to store its result in Value.

  • Namespace: Dice.AST
  • Assembly: DiceRoller (in DiceRoller.dll)

Syntax

protected internal long Evaluate(
    RollData data,
    DiceAST root,
    int depth
)

Parameters

data
Type: Dice.RollData
Configuration of the roller and roll-specific data.
root
Type: Dice.AST.DiceAST
Root of the AST.
depth
Type: System.Int32
Current recursion depth.

Return Value

Type: System.Int64

Total number of rolls taken to evaluate this subtree.

Remarks

This method is responsible for evaluating an AST, and tracks things like recursion depth and total number of rolls (throwing DiceException if they get too high). It calls EvaluateInternal to actually perform the evaluation logic (as this method is not virtual). After this method succeeds, Evaluated is set to true on the node.

When a subclass is inside of EvaluateInternal, it should call Evaluate on any child nodes it has before executing its own logic. These calls should typically increase the depth by 1.

Examples

The following example implements a new subclass of DiceAST which evaluates child nodes in its own evaluation process.

using System.Text;
using System.Collections.Generic;
using Dice.AST;

class MyNode : DiceAST
{
    private List<DieResult> _values = new List<DieResult>();

    public DiceAST Child { get; private set; }
    public override IReadOnlyList<DieResult> Values => _values;

    public MyNode(DiceAST child)
    {
        Child = child ?? throw new ArgumentNullException(nameof(child));
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        bool needParens = Child.UnderlyingRollNode is MathNode;

        if (needParens)
        {
            sb.Append("(");
        }

        sb.Append(Child.ToString());

        if (needParens)
        {
            sb.Append(")");
        }

        sb.Append("++");

        return sb.ToString();
    }

    protected override long EvaluateInternal(RollData data, DiceAST root, int depth)
    {
        long numRolls = Child.Evaluate(data, root, depth + 1);
        MyCustomLogic();

        return numRolls;
    }

    protected override long RerollInternal(RollData data, DiceAST root, int depth)
    {
        long numRolls = Child.Reroll(data, root, depth + 1);
        MyCustomLogic();

        return numRolls;
    }

    private void MyCustomLogic()
    {
        Value = Child.Value + 1;
        ValueType = ResultType.Total;
        _values.Clear();
        _values.Add(new DieResult()
        {
            DieType = DieType.Literal,
            NumSides = 0,
            Value = Value,
            Flags = 0
        });
    }
}