Sub topic 2
Simple rules as building blocks
This chapter assumes you can write loops, functions, dictionaries and sets in Python. It also assumes you know the basic game loop idea: a game keeps state and updates it in discrete ticks or turns. The previous chapter gave a working definition of emergent gameplay. Here we look at its raw material, the individual rule, and at what makes a rule suitable for combining with others.
What counts as a rule
A rule is a small, self-contained statement of the form "when this condition holds in the state, this change happens." Every rule has three parts:
- Condition: what the rule looks at. Examples are "this tile is burning" and "this unit has the
poisonedtag". - Effect: what the rule changes. Examples are "the tile becomes ash" and "the unit loses 2 hit points".
- Scope: which part of the state the rule reads and writes. Examples are "this tile and its four neighbors" and "one unit".
Players see the results of rules, not the rules themselves. A player who watches fire spread across a field is reacting to one condition-and-effect pair applied many times. That pair is "a burning tile ignites flammable neighbors."
Here is what separates a rule from a script:
| Aspect | Scripted behavior | Rule-based behavior |
|---|---|---|
| Trigger | A specific event: "when the player enters room 4" | A state pattern: "when any tile is adjacent to fire" |
| Applies to | One named object or moment | Every object that matches the condition |
| Designer knows the outcome | Yes, because it was authored | Only partly, because it depends on the state |
| Cost of more content | One new script per situation | Often no new rule at all |
A scripted bridge collapse happens once, where the designer placed it. A rule that says "a support tile that burns is removed, and anything standing on a removed tile falls" collapses every bridge in the game, including ones the designer never thought of.
Properties of a good building block
Rules that combine well tend to share five properties.
- General. The condition names a category (a tag, a type, a numeric range), not a specific object. "Flammable things burn" is general. "The wooden door in level 3 burns" is not.
- Single-purpose. The rule does one thing. If you describe it with "and", consider splitting it.
- Local. The rule reads and writes a small piece of the state, such as one cell, one unit or one pair of units. Local rules are easy to reason about, and a global pattern can still arise from many local applications. The next chapter covers this in detail.
- Explicit about its state. Everything the rule needs is in the shared state. A rule that relies on a hidden variable inside another rule's code cannot be combined safely.
- Understandable alone. A designer or player can predict what the rule does in isolation. The surprises should come from combining rules, not from any single rule being obscure.
Rules as functions over shared state
In code, a rule is easiest to manage as a function. It receives some state and returns the changes it wants, rather than modifying the state in place. This choice matters, and the next section explains why.
The example below uses units with tags. Two rules, poison and regen, each return a change to hit points (hp). The engine adds up all changes and applies them at once, capped at the unit's maximum.
def poison(unit):
"""Poisoned units lose 2 hp per tick."""
return {"hp": -2} if "poisoned" in unit["tags"] else {}
def regen(unit):
"""Units with regen gain 1 hp per tick."""
return {"hp": +1} if "regen" in unit["tags"] else {}
def apply_rules(units, rules):
"""Every rule reads the old state. All changes are summed, then applied."""
deltas = []
for unit in units:
total = {}
for rule in rules:
for key, amount in rule(unit).items():
total[key] = total.get(key, 0) + amount
deltas.append(total)
return [
{**u, "hp": min(u["hp"] + d.get("hp", 0), u["max_hp"])}
for u, d in zip(units, deltas)
]
units = [
{"name": "Ana", "hp": 10, "max_hp": 10, "tags": {"poisoned", "regen"}},
{"name": "Bo", "hp": 10, "max_hp": 10, "tags": {"poisoned"}},
{"name": "Cy", "hp": 10, "max_hp": 10, "tags": {"regen"}},
]
after = apply_rules(units, [poison, regen])
print([(u["name"], u["hp"]) for u in after])
# [('Ana', 9), ('Bo', 8), ('Cy', 10)]Neither rule mentions the other. Ana ends up at 9 hp because the two effects sum to -1. Cy is capped at 10 because the engine applies the maximum after combining. Nobody wrote an "poison and regen together" case. That outcome comes from the rules sharing a state variable, hp.
The same pattern extends. If you add a bleed rule tomorrow, it combines with both existing rules without any change to them.
Why the order of rules must not matter
Suppose the engine applied rules one after another, each modifying hp directly. Then the cap on maximum hp could be applied between the rules, and the result would depend on the order. Ana at 10 hp with regen first would gain nothing (already at max) and then lose 2 from poison, ending at 8. With poison first she would drop to 8 and then regen to 9. Same rules, different outcomes.
This is a common source of bugs in rule systems. There are two standard remedies:
- Double buffering. Each rule reads from the old state and writes into a new copy. The Game of Life example in the topic plan does this: it builds a new set of live cells from the old one.
- Collecting deltas. Rules return proposed changes and the engine combines them, as in
apply_rulesabove.
Either way, the rule author can assume "I see the state as it was at the start of this tick." That assumption is what makes each rule understandable alone.
Rules read tags, not names
The poison example checks for a tag, not for a unit's name or type. This is the most useful habit for making rules general. Compare two ways to write the same idea.
A special-case rule:
def burn_special(unit):
if unit["name"] in ("Wooden Door", "Hay Bale", "Straw Hut"):
return {"hp": -3}
return {}A general rule:
def burn(unit):
"""Burning units lose 3 hp per tick."""
return {"hp": -3} if "burning" in unit["tags"] else {}The general version has no list to maintain. Any object that gains the burning tag takes damage, whether it is a door, a unit or an object you add next month. The special-case version needs editing for every new object and says nothing about why those three belong together.
A tag is a name for a property that rules care about. Later chapters build a full tag system. For now, the working test is this: if you add a new kind of object, can existing rules affect it without being edited? If so, the rules are general enough.
Rule count versus situation count
The reason to prefer a few simple rules is arithmetic. Say you have five general rules, each reacting to one tag, and an object can carry any subset of those tags. That gives 2^5 = 32 distinct tag combinations for one object. Rules also act between objects, so the number of situations across a map is much larger. A designer who scripts situations pays per situation. A designer who writes rules pays per rule, and the situations follow.
This count is not a promise of interesting play. Many combinations will be dull, redundant or identical in effect. The point is only that rule-based content scales differently from scripted content, and that the designer's work shifts from authoring outcomes to choosing which rules exist.
Common errors
These problems appear repeatedly when people first build rule systems.
- The rule is secretly a script. The condition checks a specific name, position or level number. Replace it with a tag or a numeric condition.
- The rule does too much. "Fire spreads, damages units and makes smoke" is three rules. Split it. Separate rules let players discover that smoke can exist without fire, if some other rule produces it.
- Rules write to each other's private variables. If the
regenrule edits a counter that onlypoisonis supposed to use, the two are coupled. Keep shared variables few and obvious, such ashp, and let each rule add its own contribution. - Order dependence. Covered above. Use deltas or a copied state.
- Rules that never fire. A rule whose condition can never be true in practice adds code but no play. Check that each rule triggers in actual runs.
- Rules that always fire. A condition so broad that it applies to everything is a constant, not a rule. It adds no variety.
- Unbounded numbers. A rule that adds to a value with no cap or counter-rule will eventually dominate the state. The hp cap in the example is the simplest case. Chapter 7 treats this as a feedback problem.
A checklist before you add a rule
- State the condition and the effect in one sentence each. If you cannot, split the rule.
- Name the state the rule reads and writes. Make sure all of it lives in the shared state.
- Replace any specific names with tags or numeric tests.
- Decide how the rule's changes combine with other rules' changes: sum, maximum, last wins or error.
- Run the rule alone in a tiny test and check the result matches your one-sentence description.
- Run it together with the existing rules and look at what the combination does. Note anything you did not expect, because that is the start of emergent behavior and the topic of the chapters ahead.
Exercise
In the apply_rules example, Dee has 5 hp, max 10, and the tags poisoned and regen. What is her hp after one tick? Then explain why the result would be different if each rule modified hp directly in sequence and capped it at 10 after every rule, with regen applied first. Use a unit at 10 hp to show the difference.
Show answer
Dee loses 2 and gains 1, so her hp is 5 - 2 + 1 = 4. For the ordering question, take a unit at 10 hp with both tags. With summed deltas the change is -1, giving 9. With sequential application and a cap after each rule, regen first gives min(10 + 1, 10) = 10 and then poison gives 8. Poison first gives 8 and then regen gives 9. The result depends on rule order (8 or 9) and differs from the summed result (9 in one order, 8 in the other), which is why the engine should combine deltas before clamping.
Exercise
A designer writes the rule: "If the unit's name is 'Ice Golem' and it is next to a tile named 'Lava', it takes 5 damage." Rewrite it as a general rule using tags, and name one new object that would then be affected without any rule edits.
Show answer
Give lava the tag hot and ice-based objects the tag melts, then write: "A unit with the melts tag that is adjacent to a tile with the hot tag takes 5 damage." The Ice Golem gets melts and the Lava tile gets hot. A new object such as a Snow Hare with the melts tag, or a Fire Pit with the hot tag, is affected immediately, with no change to the rule.
Exercise
You have a rule "poisoned units lose 2 hp" and a rule "units standing in water lose the poisoned tag." Each reads the old state. A poisoned unit steps into water this tick. Does it take poison damage this tick? What does your answer show about reading old state?
Show answer
Yes, it takes the damage. Both rules read the old state, where the unit still has poisoned. The water rule removes the tag in the new state, so the unit is cured starting next tick. This shows that rules reading the same old state act "simultaneously": a rule never sees another rule's effect within the same tick, so the outcome does not depend on the order the rules run in.