← Back to Here To Slay

Here To Slay, part 7: a new engine for the rules

Why the effects system from part 2 stopped scaling once the real deck arrived, how each card became a script of steps that can stop and wait for the player, and what it was like to think this change through.

#tecnico

The new interface from part 5 assumed things the old engine couldn’t do. It was designed for effects that ask a question, show the result and ask another, and for a deck with every card in the base game. Underneath, the rules still ran on the effects system from part 2, and that system had hit its limit.

Where the old model got stuck

Up to this point, the game had 14 playable cards: 12 heroes and 2 magic cards. The rest didn’t exist, and not for lack of time. The comment at the top of the card factory itself admitted the problem: several cards used an “MVP simplification”, because the real effect would need a second selection round that the state machine didn’t support.

The reasons were the two details I wrote down at the end of part 2, now with the real deck on top of them:

  • The choice lived inside the effect. The chosen targets were stored in the effect object itself. Because of that, the factory had to create fresh instances of every effect for each copy of a card, or two identical copies would share the same targets.
  • Match found the questions with instanceof. Those type checks were spread across the hero class and the match. Every new kind of target needed a new if in several methods.
  • One state per kind of question. SELECTING_CARDS, SELECTING_HAND_CARDS and SELECTING_PLAYER, each with its own message to the client. And a card could only ask one question, always before it started.

Adding a new card meant touching three or four different places, and many cards simply didn’t fit. Bear Claw, for example, says: “pull a card from another player’s hand; if it’s a hero, pull another”. That’s two decisions, with a condition in between that depends on the result of the first. In the old model, the second card would have to be picked at random.

Effects before and after: from effects that stored the choice and were detected with instanceof to a single GameCard with a Script built from Ctx blocks

How to think about the change

The turning point came from looking at the card’s text instead of the code. The text of a Here To Slay card already is a script: choose a player, pull a card, if it’s a hero, pull another. They’re steps in order, and some of them stop to ask someone something.

So an effect shouldn’t be an object that executes everything at once, but a list of steps that the match runs through. And the match should be a queue that knows how to pause: when a step needs an answer, it stops, waits for the player and carries on exactly where it was.

With that idea, the engine was written next to the old system, without touching it: first the core, then the card and monster catalogs. Only once the pieces were ready did the match start running on them, in a single switch.

The pieces

There’s now a single card class, GameCard, with a kind (hero, magic, item, modifier or challenge), and each card’s effect is a Script: a function that returns the list of steps.

@FunctionalInterface
public interface Script {
    List<Runnable> steps(Ctx ctx);
}

Steps are built from ready-made blocks in Ctx, the context of the card being played: choosePlayer, pull, draw, discard, destroy, searchDiscard, when and others. Ctx also keeps what each step chose, as a kind of variable memory, and that was exactly what was missing: one step writes "target", the next one reads it. Bear Claw ended up almost identical to the card’s text:

hero("Bear Claw", FIGHTER, 7, c -> List.of(
        c.choosePlayer("target", p -> !p.getHand().isEmpty()),
        c.pull(c.varOf("target"), 1, "pulled"),
        c.when(() -> c.firstIs("pulled", HERO), c.pull(c.varOf("target"), 1, "pulled2")))),

Bear Claw in three steps: choose a target with cards in hand, pull a card and, if it’s a hero, pull another

One important detail: Ctx methods don’t do anything when they’re called. Each one returns a Runnable, the step, which only runs when its turn comes. When a step needs a decision, it doesn’t decide: it asks and says what to do with the answer.

public Runnable choosePlayer(String var, Predicate<PlayerState> filter) {
    return () -> {
        List<JSONObject> options = t.others(owner).stream().filter(filter).map(Ctx::playerOption).toList();
        t.ask(owner, "choose_player", params(), options.isEmpty() ? 0 : 1, 1, options, source,
                sel -> set(var, sel.isEmpty() ? null : sel.get(0)));
    };
}

That t is the Table, an interface with everything an effect can do in a match: draw, discard, destroy, steal, ask. The match implements this interface, and effects don’t know anything else about it.

Put together, the class diagram ended up much smaller than the one in part 2. A card no longer has subclasses or effects hanging off it: it only carries a Script, and everything that changes during a match (the queue of steps, the open question, the roll in progress) lives in Match.

Class diagram of the new engine: Match implements Table and holds the queue of steps, the pending choice and each player’s state; each GameCard has a Script that returns steps built with Ctx; CardCatalog builds the deck

The queue that pauses

The heart of the engine is small. The match keeps pending steps in a queue, and a loop runs one at a time until the queue is empty or someone needs to answer:

public void push(List<Runnable> steps) {
    for (int i = steps.size() - 1; i >= 0; i--) flow.addFirst(steps.get(i));
}

private void pump() {
    // ...
    while (!waiting && !flow.isEmpty() && phase == Phase.GAMEPLAY) flow.pollFirst().run();
}

When a step asks something, the queue pauses. When the answer arrives, it goes into Ctx and the queue carries on. And since steps like when put their sub-steps at the front of the queue, everything works like a function call in the middle of the card: the “if it’s a hero, pull another” runs right after the first pull, before anything else.

That also changed the state machine. In part 2, every kind of question was a match state. Now the match has only five phases, and inside the game only one thing is happening: the queue running steps. Questions, challenge windows, duels and rolls are no longer match states, but reasons for the queue to wait. In code, the state is the Phase enum plus whichever pending field is set on Match (choice, challengeWindow, duel, roll or modifierWindow), and each transition happens through a client message, an event or a deadline:

State machine as implemented: the Phase enum with LOADING, ORDER_SELECTION, PARTY_LEADER_SELECTION, GAMEPLAY and FINISHED; inside GAMEPLAY, idle() waits for the current player’s action, pump() runs the queue and pauses when choice, challengeWindow, roll, duel or modifierWindow are set; each transition shows the message that triggers it, such as order_selection, choose_party_leader, play_card, challenge, process_challenge_roll, select_effect_target, play_modifier and pass, and events such as order_finalized, duel_start and match_finished

Notice that every pause has a deadline. A choice nobody answers gets an automatic answer after 60 seconds, whoever doesn’t roll gets their dice rolled for them, and the challenge and modifier windows close on their own. No player can freeze the table, not even by dropping in the middle of a question.

One way to ask

With this, choosing a player, a card from a hand or a hero on the table became the same thing: a Choice, with the question’s text, the options and how many can be chosen. The three SELECTING_* states and the instanceof checks were gone.

Having a single kind of question also made room for an improvement that came right after: everyone sees the same choice screen. The chooser sees the real options. Everyone else sees the same options when they’re already public, like a hero on the table, or face down when they come from a hidden place, like someone’s hand. Nobody is left staring at a frozen table without knowing what’s going on.

The client also started receiving a single, complete match state instead of a bunch of separate messages for each situation. That state feeds the animations from part 5, and it’s what later made it possible to return to a match at the exact point after reloading the page.

In part 8, what happened when I took the game off my machine and other people started playing.