Sub topic 6
Building a Tag-Based Interaction System
Assume you know loops, functions, dictionaries, and sets. You should also be familiar with games that update their state in discrete turns or ticks. This chapter uses those ideas to build interactions without writing a separate conditional for every pair of objects.
Why use tags?
A tag is a small label that describes a property or role. An object might have tags such as fire, water, or fuel. Tags are more flexible than fixed object types because one object can have several properties at once.
For example, a barrel might have these tags:
fuel, wooden, movableA burning barrel might have:
fire, fuel, wooden, movableThe interaction system does not need to know that the object is a barrel. It only checks the tags involved. This lets the same rule work with grass, oil, wood, or any future object that receives the fuel tag.
A rule can be represented as a relationship between a source tag and a target tag:
| Source tag | Target tag | Result |
|---|---|---|
| fire | fuel | Target becomes fire |
| fire | water | Fire becomes steam and water becomes steam |
| water | fire | Same relationship in the opposite direction, if needed |
The important design choice is that the interaction engine stays general. The data describes what changes. The engine applies those changes.
Representing interactions as data
A rule needs to describe four possible changes:
- Tags to add to the source.
- Tags to remove from the source.
- Tags to add to the target.
- Tags to remove from the target.
The following program stores these changes in Rule objects. The tick function does not contain a fire branch, a water branch, or a fuel branch. It only matches tags and applies the declared changes.
from dataclasses import dataclass
from typing import FrozenSet
@dataclass(frozen=True)
class Rule:
source_tag: str
target_tag: str
add_source: FrozenSet[str] = frozenset()
remove_source: FrozenSet[str] = frozenset()
add_target: FrozenSet[str] = frozenset()
remove_target: FrozenSet[str] = frozenset()
RULES = (
Rule(
"fire",
"fuel",
add_target=frozenset({"fire"}),
remove_target=frozenset({"fuel"}),
),
Rule(
"fire",
"water",
add_source=frozenset({"steam"}),
remove_source=frozenset({"fire"}),
add_target=frozenset({"steam"}),
remove_target=frozenset({"water"}),
),
)
NEIGHBORS = (-1, 1)
def tick(cells: dict[int, set[str]]) -> dict[int, set[str]]:
"""Apply all interactions using the state at the start of the tick."""
next_cells = {position: set(tags) for position, tags in cells.items()}
for source in cells:
for offset in NEIGHBORS:
target = source + offset
if target not in cells:
continue
for rule in RULES:
if (
rule.source_tag in cells[source]
and rule.target_tag in cells[target]
):
next_cells[source] -= rule.remove_source
next_cells[source] |= rule.add_source
next_cells[target] -= rule.remove_target
next_cells[target] |= rule.add_target
return next_cells
def show(cells: dict[int, set[str]]) -> None:
print(" | ".join(
f"{position}:{','.join(sorted(tags))}"
for position, tags in sorted(cells.items())
))
world = {
0: {"fire"},
1: {"fuel"},
2: {"water"},
}
for turn in range(3):
print(f"turn {turn}: ", end="")
show(world)
world = tick(world)At the first tick, fire adds the fire tag to the fuel cell and removes its fuel tag. At a later tick, that new fire reaches the water. The same generic operations then replace fire and water with steam.
The copy named next_cells matters. Every rule reads from cells, which is the state at the beginning of the tick. Without this separation, a newly created fire could act again immediately during the same update. That would make outcomes depend on loop order.
Composing tags safely
Tags create combinations automatically. A cell can be both fire and fuel, or both water and movable. This supports richer systems, but it also creates questions:
- Does a cell with
fireandwaterextinguish itself? - Can steam become water when it reaches a cold region?
- Does a fuel cell disappear when it burns, or only lose its
fueltag? - If two rules match, do both apply, or does one have priority?
Write these policies down before adding many rules. Otherwise, the order of rules in a list may become an accidental game mechanic.
A useful extension is to add rule priority or a maximum number of interactions per cell. Another is to separate detection from resolution: first collect all matching rules, then resolve conflicts according to an explicit policy.
Exercise
Add a rule that makes water remove the fire tag from a neighboring target without removing either object. Which fields should the rule change?
Show answer
Use source tag water, target tag fire, and set remove_target to {"fire"}. Leave the add and remove fields for the source empty.