Skip to content

Systems and dice

A system is a game's rules: entity schemas, sheets, dice and initiative. Full system plugins (kind system, with entity schemas, sheets in frames and a declarative dice spec) arrive with milestone M3. What 0.3.0 has is the dice half, on both sides:

  • On the server, a DiceSystem that the host provides draws every number that matters and returns a RollResult. Its ext carries the system's own data to the browser.
  • In the browser, a system's client plugin reads the results: dice.classify marks single dice, dice.summary writes one line under the total. The diceSystems registry rolls for pages without a server.

The running example is a Powered-by-the-Apocalypse system: 2d6+1 Go aggro rolls two six-sided dice plus one, and the tray says "Go aggro: weak hit, at a cost". Both halves are in docs/examples/ and are run by tests (server/taflor_server/tests/test_docs_generated.py, server/taflor_server/tests/js/test_docs_examples.mjs).

On the server: a dice system

The server never runs plugin code; the dice system is Python that the host provides (TableHost.dice_system(table)), from its own code or from a server extension. Without one, the core rolls standard expressions itself: NdS and NdS±M, summed, nothing explodes, no classes.

"""A dice system on the server (SPEC §8.5): "2d6+1 Go aggro" rolls 2d6 plus one, and tells its
client plugin which move was rolled through ``RollResult.ext``. The systems guide's example
(docs/how-to/systems.md); server/taflor_server/tests/test_docs_generated.py rolls it."""

import re

from taflor_server.host import DieFace, RollResult

MOVE = re.compile(r"^\s*2d6\s*(?:([+-])\s*(\d{1,2}))?\s*(.*?)\s*$", re.IGNORECASE)


class PbtaDice:
    id = "pbta"
    #: The declarative spec the client gets; this system needs none.
    spec = {}

    def parse(self, expression):
        match = MOVE.match(expression or "")
        if match is None:
            raise ValueError(f"not a move roll: {expression!r}")
        sign, amount, move = match.groups()
        modifier = int(amount or 0) * (-1 if sign == "-" else 1)
        return {"modifier": modifier, "move": move}

    def evaluate(self, plan, context, rng):
        faces = [DieFace(6, rng.randint(1, 6)) for _ in range(2)]
        total = sum(face.value for face in faces) + plan["modifier"]
        return RollResult(
            expression=f"2d6{plan['modifier']:+d}" if plan["modifier"] else "2d6",
            dice=faces,
            total=total,
            classes=["success"] if total >= 10 else ["fail"] if total < 7 else [],
            detail={"modifier": plan["modifier"]},
            # For the client plugin, under this system's id; JSON, small, not too deep.
            ext={"pbta": {"move": plan["move"]}} if plan["move"] else {},
        )

    def initiative(self, record, token):
        # PbtA games have no initiative: the combat tracker asks for it by hand.
        return None

The protocol, in taflor_server.host:

member what
id the system's id; it also keys its data in RollResult.ext
spec the declarative spec the client gets ({} when there is none)
parse(expression) a plan of your own; ValueError for input it can't roll
evaluate(plan, context, rng) a RollResult; draw with rng (randint, random), never with your own generator
initiative(record, token) an InitiativeSpec (expression, tiebreak), or None: the tracker asks for it by hand

RollResult has expression, dice (each DieFace: sides, value, exploded, rerolled), total (None when a roll has no sum), classes, detail and ext:

  • classes classify the whole roll. The tray and the log mark megacrit, crit, success and fail, the first one that matches in that order; other names are kept and passed on.
  • detail is the system's breakdown; detail["modifier"] shows in the roll's line.
  • ext is the system's own data for its client plugin, a JSON object keyed by system ids: {"pbta": {"move": "Go aggro"}}. At most 4096 bytes encoded and 16 levels deep; anything else is refused with ValueError. It goes with the roll in dice.rolled and in the roll log. Players get ext as null for a roll on a token hidden from them, because a system's data can tell whose roll it was. Rolls from older servers have no ext; read it as {}.

The roll log

The host keeps the log, if it wants one (TableHost.roll_log(table), None for no log). The core gives every roll a roll_id and a server time at, and calls RollLog.record(game, table, user, actor, result, visibility, entry) with the log entry: the fields of dice.rolled the dice log shows, as the GM gets them, ext included. Store entry as given, including entry["ext"] (the checked copy), never the raw result.ext. RollLog.history(game, user, cursor, limit) returns {"records": [entry, ...], "cursor": <the next older page> or None}, newest first; the core shapes each entry for its reader.

Rolls made outside the table (a sheet, another page of the host) reach it through api.broadcast_roll(...), with record=True to log them like table rolls.

In the browser: reading the results

The browser never decides a roll; it shows the server's. A system's client plugin explains a result through two providers, exclusive slots of the hook catalogue:

// The example of the systems guide (docs/how-to/systems.md): the two dice providers. The server
// rolls; this plugin only reads the result it gets, in frozen copies. Its test is
// server/taflor_server/tests/js/test_docs_examples.mjs.

/** The data a server-side dice system put into `RollResult.ext`, under its id. */
const own = (roll) => roll.ext?.pbta ?? {};

/** @type {import("@taflor/api").Plugin} */
export default {
  activate(ctx) {
    const t = ctx.plugin.t;
    // One line under the total, plain text, asked when the roll is shown (the reader's language).
    ctx.hooks.provide("dice.summary", (roll) => {
      if (typeof roll.total !== "number") return null;
      const move = own(roll).move ? `${own(roll).move}: ` : "";
      if (roll.total >= 10) return move + t("hit.strong");
      if (roll.total >= 7) return move + t("hit.weak");
      return move + t("miss");
    });
    // The chips of single dice: a six marks as "success", a one as "fail".
    ctx.hooks.provide("dice.classify", (die) => (die.value === die.sides ? ["success"] : die.value === 1 ? ["fail"] : []));
  },
};
  • dice.classify(die, roll) → string[] gives the classes of one die for its chip in the tray and the dice log. die and roll are frozen copies; roll.ext is there. The roll's own classes come only from RollResult.classes on the server.
  • dice.summary(roll) → string | null gives one line under the total on the tray's card and in the dice log. It is asked when the roll is shown, so it is in the reader's language. It is plain text, never HTML, cut to 200 characters; a provider that throws shows nothing.

Both run for every shown roll, so keep them cheap and pure: no network, no state.

A provider slot holds one provider. A second plugin that provides dice.summary fails to activate and is rolled back, with both plugins named.

Rolling without a server

The pages without a server - the dev harness, the sandbox, the website's demo - roll in the browser, through the diceSystems registry. The bundled standard plugin registers its standard system there (server/taflor_server/plugins/standard/): a def with parse, evaluate and initiative.

parse(expression) returns a plan or throws, evaluate(plan, context, random) returns a RollResult (same shape as the server's), initiative(record) an InitiativeSpec or null. In 0.3.0 these pages always roll with standard; real tables always roll on the server.