Skip to main content

Code frameworks

Recipe: clamp a value

Keep a value inside a range with math.max and math.min.

Goal

Stop HP from going below zero when a Keeper takes damage.

The change

Read the current value, then write the clamped result.

rules/hurt.ts
export function hurt(self: ElementRef, amount: number): void {
  const hp: number = element.var(self, "hp") as number;
  ledger.set(self, "hp", math.max(0, hp - amount));
}
  1. Line 2 Read the current HP.
  2. Line 3 math.max keeps the result at 0 or above. Write the final value with ledger.set.

Use math.min(limit, value) to keep a value at or below a limit.

A limit can be another field. To keep Sanity at or below a max_sanity field, read both and write math.min(max_sanity, sanity + amount). The heal rule in the quickstart does this with max_hp. Test the capped step.

Test it

The rule now sets a value, so the expected write is ledger.set instead of ledger.add. Add a step that would go below zero.

scenarios/heal.json
  "actions": [
    {
      "action": "hurt",
      "parameters": { "amount": 6 },
      "expectedWrites": [{ "op": "ledger.set", "key": "hp", "value": 4 }]
    },
    {
      "action": "hurt",
      "parameters": { "amount": 20 },
      "expectedWrites": [{ "op": "ledger.set", "key": "hp", "value": 0 }]
    },
    {
      "action": "heal",
      "parameters": { "amount": 3 },
      "expectedWrites": [{ "op": "ledger.set", "key": "hp", "value": 3 }]
    }
  ]
  1. Lines 7-11 Take 6 damage: 10 minus 6 is 4.
  2. Lines 12-16 A hit of 20 would go below zero. The rule writes 0.
  3. Lines 17-21 Heal 3 from 0.

Next