Skip to main content

Code frameworks

Recipe: a derived stat

Calculate a value from other values with a ledger function.

Goal

Show a Ward that is half of the maximum HP, rounded down.

The change

Declare the function in the schema.

schemas/keeper.json
  "ledgerFunctions": [
    {
      "id": "ward",
      "name": "Ward",
      "field": "ward",
      "source": "rules/ward.ts"
    }
  ]
  1. Lines 19-22 field is the stored value Ward fills.
rules/ward.ts
export function ward(currentValue: number, self: ElementRef): number {
  const max_hp: number = element.var(self, "max_hp") as number;
  return math.floor(max_hp / 2);
}
  1. Line 1 currentValue is the value so far. Most derived values ignore it.
  2. Line 2 Read what you need with element.var.
  3. Line 3 Return the derived number.

The constructor still returns the field, with a starting value of 0.

rules/keeper.ts
export function construct(
  name: string,
  max_hp: number,
): { name: string; max_hp: number; hp: number; ward: number } {
  return { name: name, max_hp: max_hp, hp: max_hp, ward: 0 };
}
  1. Lines 4-5 ward is returned as 0. The ledger function derives it right after.

Test it

scenarios/new-keeper.json
  "ledger": [{ "function": "ward", "currentValue": 0, "expected": 5 }]
  1. Line 6 Checks the function: it starts from 0 and must return 5.

Also add ward to expectedValues in every scenario for the Keeper.

Next