Sub topic 6
Building a tag-based interaction system
This chapter assumes you can read Python with sets, dataclasses and loops. It also assumes you know the earlier chapters' idea that a game updates shared state in discrete ticks, and that general rules which combine orthogonally produce more situations than special cases do. Here you turn that idea into a working data structure and engine.
The problem: special cases multiply
Suppose your game has fire, water, wood, grass, metal and electricity. The obvious way to code interactions is a function per pair:
if fire hits wood: ignite it
if fire hits water: extinguish fire
if electricity hits water: shock everything inside
...With N kinds of things you may need N × N cases. Each new material forces you to revisit every existing one. Most of those cases are also the same fact repeated: wood, grass and cloth all burn.
A tag-based system moves the shared fact into data. Each entity carries a set of tags such as flammable, wet or conductive. Rules never mention "wood" or "grass". They mention tags. A new material is only a new set of tags, and it takes part in every existing interaction that matches them.
| Approach | Cost of adding a material | Cost of adding an interaction | Where the behavior lives |
|---|---|---|---|
| Pairwise special cases | Edit up to N existing cases | One new case per affected pair | Scattered across code |
| Tags and rules | Write one tag set | Write one rule | A single rule list |
The model: tags, rules and a tick
The model has three parts.
- State. Each cell of a grid holds a set of tags.
- Rules. A rule says: if a cell has all the tags in
needs, has none of the tags inblocked_by, and (optionally) has a neighbor with the tagsource, then remove some tags and add others. - A tick. Every cell is evaluated against the old grid. All changes are written to a new grid.
Reading from the old grid and writing to a new one keeps the result independent of scan order. This is the same discipline the Game of Life code uses. Without it, fire would race across the whole row in one tick because each newly ignited cell would be seen by the next cell in the loop.
Implementation
The engine below is the whole system. Run it as one file with Python 3.8 or later.
from dataclasses import dataclass
from typing import Optional
NEIGHBORS = ((1, 0), (-1, 0), (0, 1), (0, -1))
def tags(*names):
return frozenset(names)
@dataclass(frozen=True)
class Rule:
name: str
needs: frozenset # tags the cell itself must have
add: frozenset = frozenset()
remove: frozenset = frozenset()
source: Optional[str] = None # tag a neighbor must have; None means self-only
blocked_by: frozenset = frozenset() # tags that stop the rule
def tick(grid, rules):
h, w = len(grid), len(grid[0])
new = []
for y in range(h):
row = []
for x in range(w):
here = grid[y][x]
adds, removes = set(), set()
for rule in rules:
if not rule.needs <= here or rule.blocked_by & here:
continue
if rule.source is not None and not any(
0 <= x + dx < w
and 0 <= y + dy < h
and rule.source in grid[y + dy][x + dx]
for dx, dy in NEIGHBORS
):
continue
adds |= rule.add
removes |= rule.remove
row.append(frozenset((here - removes) | adds))
new.append(row)
return new
def show(grid):
return [["+".join(sorted(t)) for t in row] for row in grid]
RULES = [
Rule("ignite", needs=tags("flammable"), source="burning",
blocked_by=tags("wet", "burning"), add=tags("burning")),
Rule("soak", needs=tags("flammable"), source="water",
blocked_by=tags("wet"), add=tags("wet")),
Rule("burn_out", needs=tags("burning"),
remove=tags("burning", "flammable"), add=tags("ash")),
]
grid = [[
tags("flammable", "burning"),
tags("flammable"),
tags("flammable"),
tags("water"),
tags("flammable"),
]]
for _ in range(2):
grid = tick(grid, RULES)
print(show(grid)[0])
# ['ash', 'ash', 'flammable+wet', 'water', 'flammable+wet']Follow the two ticks by hand, because this is the habit that lets you debug the system later.
- Tick 1. The first cell burns out and becomes
ash. The second cell has a burning neighbor and is flammable, so it ignites. The third and fifth cells touch water, sosoakmakes themwet. - Tick 2. The second cell burns out. The third cell now has a burning neighbor, but
wetis in itsblocked_by, so it does not ignite.
Nothing in the code mentions "water stops fire". The behavior comes from two rules and one blocking tag. The blocking tags wet and burning also matter in ignite: without burning in blocked_by, a burning cell next to another burning cell would re-ignite every tick and burn_out could never finish.
Adding a mechanic without touching old rules
Now add electricity. The new rules refer to new tags, and they reuse flammable, wet and burning from the old ones.
RULES_V2 = RULES + [
Rule("conduct", needs=tags("conductive"), source="electrified",
blocked_by=tags("electrified", "spent", "insulated"),
add=tags("electrified")),
Rule("discharge", needs=tags("electrified"),
remove=tags("electrified"), add=tags("spent")),
Rule("spark", needs=tags("flammable"), source="electrified",
blocked_by=tags("wet", "burning"), add=tags("burning")),
]
cable = tags("conductive")
row = [
tags("conductive", "electrified"),
cable,
tags("water", "conductive"),
cable,
tags("flammable"),
]
grid = [row]
for _ in range(4):
grid = tick(grid, RULES_V2)
print(show(grid)[0])
# ['conductive+spent', 'conductive+spent', 'conductive+spent+water',
# 'conductive+spent', 'burning+flammable']Run this after the first block, in the same file. A pulse travels along the cable, crosses the water tile because water carries conductive, and ignites the dry grass at the end. If the grass had been adjacent to the water, soak would have made it wet and the spark would have been blocked. That interaction between two mechanics was never written down by anyone.
The spent tag solves a problem you will meet in many tag systems. Without it, the pulse would bounce back: after a cell discharges, its neighbor is still electrified, so conduct would re-electrify it. A tag that records "this already happened" gives the system short-term memory. It is a small piece of state added to prevent an unwanted loop.
Design decisions and failure modes
Choose tags that name properties, not objects
flammable, conductive and heavy describe how something behaves. wood and sword describe what it is. If you find a rule that needs wood, you are probably missing a property tag, and the rule should use that instead. Keep object identity for display and tag sets for simulation.
Tag explosion
Each tag is a promise that some rule will use it. A tag no rule reads is dead weight. A tag that many rules read with different meanings (for example, hot meaning "can ignite" in one rule and "can melt" in another) forces you to split it. Review the tag list when you add a rule. Delete unused tags and split overloaded ones.
Order dependence
The engine reads only the old grid, so scan order does not matter. Conflicts between rules on the same cell still exist. Here, all removals are applied before additions, so a rule that adds and a rule that removes the same tag in one tick resolve to "added". Make that policy explicit and test it. In the electricity example it is the reason conduct is blocked by electrified. Otherwise a cell's own discharge would be undone by conduct in the same tick.
Runaway chains
A positive feedback chain such as fire spreading to everything flammable is the point of the system, and it is also the main balance risk. Tags give you levers: add blocked_by tags, add a self-limiting tag like spent, or add a rule that removes flammable over time. The next chapters on feedback loops and tuning cover how to choose among these.
Debugging
Emergent bugs are hard to find because no single rule is wrong. Make the engine tell you what happened. A small change to tick can record the names of the rules that fired for each cell. When a player reports that a tile ignited for no reason, you can read the log instead of guessing.
Limits of the approach
Tags are good for binary properties and simple propagation. They are weak for quantities. Heat that accumulates, fuel that depletes, or water volume that flows need numeric state. A common compromise is to keep numbers in the entity and have a rule convert a threshold crossing into a tag, for example temperature > 100 adds burning. Tags remain the interface between mechanics, and numbers stay inside each mechanic.
Checking your understanding
Exercise
In the first code block, remove "burning" from the blocked_by set of the ignite rule. What happens to a cell that is burning next to another burning cell, and why?
Show answer
The ignite rule still matches the cell, because it is flammable and has a burning neighbor. It adds burning while burn_out removes burning and flammable. Removals are applied before additions, so burning is added back, and flammable stays removed but burning persists. The cell keeps burning and never becomes plain ash as long as a neighbor burns. Blocking on burning stops a burning cell from being re-ignited.
Exercise
Add a rule so that a wet tag dries out. It must disappear from a cell that has no neighbor with the tag water. Which fields of Rule do you need, and what is the limitation of expressing it with the current engine?
Show answer
The engine only supports positive neighbor conditions. A rule with needs=tags("wet"), remove=tags("wet") and no source would dry every wet cell every tick, including those beside water. Drying only away from water needs a negative neighbor condition, such as a source_absent field, or a counter that drains over time. The exercise shows that the engine's rule language limits which behaviors you can express as data, and that you extend the language when a rule needs a condition it cannot state.
Exercise
A designer wants metal to conduct electricity but not when it carries the tag rubber_coated. Without editing any existing rule, which change makes that work, and why does it also cover other mechanics that use the same tag?
Show answer
Add rubber_coated to the blocked_by set of the conduct rule (or reuse the existing insulated tag by tagging rubber-coated cables insulated). Because the rule checks tags and not materials, every cell with that tag is insulated, whatever it is made of. Tagging new cells insulated is the only change needed, and no material-specific code is added.