Skip to main content

Code frameworks

Recipe: spend a resource

Write an action that does nothing when a resource is gone, and test both cases.

Goal

Let a Keeper strike three sparks. A fourth does nothing.

The change

rules/spark.ts
export function spark(self: ElementRef): void {
  const charges: number = element.var(self, "charges") as number;
  if (charges > 0) {
    ledger.add(self, "charges", -1);
  }
}
  1. Line 2 Read the resource.
  2. Lines 3-5 Spend one only while some is left. Otherwise the action writes nothing.

Declare the action in the schema.

schemas/keeper.json
  "actions": [
    { "id": "hurt", "name": "Take damage", "source": "rules/hurt.ts" },
    { "id": "heal", "name": "Heal", "source": "rules/heal.ts" },
    { "id": "spark", "name": "Strike a spark", "source": "rules/spark.ts" }
  ],
  1. Line 13 The new action.

The constructor returns charges with a starting value of 3.

rules/keeper.ts
export function construct(
  name: string,
  max_hp: number,
): { name: string; max_hp: number; hp: number; charges: number } {
  return { name: name, max_hp: max_hp, hp: max_hp, charges: 3 };
}
  1. Lines 5-6 charges is a stored field with a starting value of 3.

Add an alias for the action to the Frame's dataContract and a button that uses it, or players cannot use it from the sheet.

layouts/keeper.json
      { "name": "spark", "functionRef": "spark" }
  1. Line 20 The alias for the action.
layouts/keeper.json
      { "kind": "button", "label": "Strike a spark", "actionRef": "spark" }
  1. Line 34 The button that calls it.

Test it

scenarios/spark.json
{
  "id": "spend-all-charges",
  "framework": "keeper",
  "parameters": { "name": "Mira", "max_hp": 10 },
  "expectedValues": { "name": "Mira", "max_hp": 10, "hp": 10, "charges": 3 },
  "actions": [
    {
      "action": "spark",
      "parameters": {},
      "expectedWrites": [
        { "op": "ledger.add", "key": "charges", "value": -1 }
      ]
    },
    {
      "action": "spark",
      "parameters": {},
      "expectedWrites": [
        { "op": "ledger.add", "key": "charges", "value": -1 }
      ]
    },
    {
      "action": "spark",
      "parameters": {},
      "expectedWrites": [
        { "op": "ledger.add", "key": "charges", "value": -1 }
      ]
    },
    { "action": "spark", "parameters": {}, "expectedWrites": [] }
  ]
}
  1. Lines 7-27 Three sparks each spend one charge.
  2. Line 28 The fourth finds no charges, so it expects no writes.
manifest/project.json
{
  "formatVersion": "fabled.game-project/v1",
  "projectId": "game-your-game-id",
  "projectKind": "GAME",
  "compilerProfile": "native-game-v1",
  "name": "Lantern Keepers",
  "entryFramework": "keeper",
  "frameworks": ["schemas/keeper.json"],
  "scenarios": [
    "scenarios/new-keeper.json",
    "scenarios/heal.json",
    "scenarios/spark.json"
  ]
}
  1. Line 12 The new scenario file.

List the new scenario file in the manifest. Add charges to the expected values of the other two scenarios.

Next