Sub topic 5
Combining Rules: Orthogonal Design
This chapter assumes you have read the previous chapters on simple rules and on local interaction with shared state. It also assumes you can read short Python programs. Here you will learn how to design rules so that combining them produces many situations without you having to write each situation by hand.
Why combinations are the point
One rule gives one behavior. Two rules that touch the same state give three things to consider: each rule alone, and the two together. As the rule count grows, the number of groups of rules that can act on the same thing grows much faster than the rule count does.
The table counts, for n rules, the pairs of rules and the groups of two or more rules that could be active on the same object at once.
| Rules (n) | Pairs | Groups of 2 or more |
|---|---|---|
| 3 | 3 | 4 |
| 5 | 10 | 26 |
| 8 | 28 | 247 |
| 12 | 66 | 4083 |
You can reproduce the table with this program:
from math import comb
for n in (3, 5, 8, 12):
pairs = comb(n, 2)
groups = 2**n - 1 - n # all subsets, minus the empty set and the single rules
print(f"{n} rules: {pairs} pairs, {groups} groups of 2 or more")Whether you can use this growth depends on how the rules are built. If every combination needs its own code, the growth is a cost to you. If the rules combine on their own, it is free content.
What "orthogonal" means
Two rules are orthogonal when each one does its job without knowing the other exists. The term comes from geometry, where two perpendicular axes can be moved independently. In game design it means three things:
- Each rule reads some shared state and changes some shared state.
- A rule never names another rule, and never branches on which other rules are present.
- Interactions happen only through the shared state, because one rule's output is another rule's input.
Orthogonal does not mean the rules never interact. It means they interact only through state. Fire spreading to grass and rain putting out fire do not know about each other. Both read and write a tile's condition. Where they meet, a new situation appears, such as a storm that stops a wildfire.
Entangled design versus orthogonal design
The usual way to get combinations is to write each one. A fire sword hurts an ice golem, so you add a branch. A fire sword burns a wooden door, so you add another. Every new weapon or target multiplies the branches.
The orthogonal alternative is to give things general properties and write one rule that compares them.
ELEMENT = {"fire_sword": "fire", "iron_sword": None, "torch": "fire"}
BASE = {"fire_sword": 10, "iron_sword": 10, "torch": 2}
WEAKNESS = {"ice_golem": {"fire"}, "wood_door": {"fire"}, "stone_wall": set()}
def damage(weapon, target):
"""One rule: matching an element to a weakness doubles the damage."""
bonus = 2 if ELEMENT[weapon] in WEAKNESS[target] else 1
return BASE[weapon] * bonus
print(damage("fire_sword", "ice_golem")) # 20
print(damage("iron_sword", "ice_golem")) # 10
print(damage("torch", "wood_door")) # 4
print(damage("torch", "stone_wall")) # 2The torch was added with one entry in ELEMENT and one in BASE. It then worked against every target, including the door, without any change to damage. The entangled version needs a branch per weapon and target pair, so three weapons and three targets could need nine branches. The orthogonal version needs six table entries.
| Question | Entangled design | Orthogonal design |
|---|---|---|
| Where does an interaction live? | In a branch for that specific pair | In a general rule plus data |
| Cost of adding one new thing | Grows with the number of existing things | Roughly constant |
| Can players find interactions you did not write? | Rarely | Often |
| Can you predict every outcome by reading the code? | Yes, they are listed | Not always, which is part of the appeal |
| Main risk | Content that is expensive and feels canned | Outcomes you did not intend |
The last row is the trade-off. Orthogonal design gives up some control in exchange for coverage. The later chapters on exploits, tuning and playtesting exist because of that trade.
Testing whether your rules are orthogonal
Run these checks on a design before you build it.
- Describe each rule alone. Write one sentence for each rule without mentioning another rule. "Fire turns into ash and ignites flammable neighbors" passes. "Fire is extinguished if the water rule has run" fails.
- Add a rule without editing old ones. If a new rule forces changes in existing rules, there is hidden coupling.
- Remove a rule. The others should still run correctly. They may produce duller situations, but they should not break.
- Shuffle the order. If shuffling the rules changes the result, the rules interact through execution order and not through state. The next section covers this.
- Look for rules that share no state. A rule that reads and writes data no other rule touches is perfectly orthogonal, and it also adds nothing to any combination.
The last check is easy to forget. Orthogonality is a means to rich combinations. Rules that cannot affect one another give you a longer list of features and no emergence.
Order of application: the main hidden coupling
Rules that look independent can still depend on the order in which you run them. This happens when each rule writes directly to the state while the next rule is reading it. Clamping makes it easy to see. Take a unit with 9 hit points out of a maximum of 10, which is poisoned and also regenerating.
MAX_HP = 10
def poison(unit):
return -2 if unit["poisoned"] else 0
def regen(unit):
return 3 if unit["regen"] else 0
def apply_in_place(unit, rules):
"""Each rule's effect is applied and clamped before the next rule runs."""
hp = unit["hp"]
for rule in rules:
hp = min(MAX_HP, hp + rule(unit))
return hp
def apply_snapshot(unit, rules):
"""Every rule reads the same old state. Changes are summed, then clamped once."""
total = sum(rule(unit) for rule in rules)
return max(0, min(MAX_HP, unit["hp"] + total))
unit = {"hp": 9, "poisoned": True, "regen": True}
print(apply_in_place(unit, [poison, regen])) # 10
print(apply_in_place(unit, [regen, poison])) # 8
print(apply_snapshot(unit, [poison, regen])) # 10
print(apply_snapshot(unit, [regen, poison])) # 10With in-place updates, the order of two rules changes the outcome from 10 to 8. The poison rule and the regeneration rule never mention each other, yet the program ties them together. The snapshot version removes the coupling. Every rule sees the state as it was at the start of the tick, and the changes are merged once.
The same idea applies to grid simulations. The fire example earlier in this tutorial copies the grid before updating it, so a tile that ignites during a tick cannot ignite its neighbor in that same tick. Without the copy, fire would spread across a whole row in one tick or only a little, depending on the order in which the loop visits the tiles.
Choosing a merge policy
The merge step is where orthogonal rules meet, so it deserves a decision. Common policies are:
- Sum. Used for numbers such as hit points and speed. Poison and regeneration combine into a net change. Clamp after the sum, not between rules.
- Max or min. Used for "strongest wins" fields, such as the largest damage reduction among several shields.
- Set union. Used for tags and status effects. A unit that is both wet and burning holds both tags.
- Priority. Used when only one outcome can exist, such as a tile that must be exactly one of grass, ash or water. State the priority explicitly in a table and do not leave it to the order of the code.
A priority table is a short, visible rule that a whole team can review. It prevents the situation where a later edit moves one line and changes how fire and water resolve.
Common failure modes
- Hidden special cases. A "tiny" exception such as "except in the swamp" makes one rule know about another. Once you have three of these, the design is entangled again. Move the exception into data, such as a tag on the swamp tiles that the rule reads.
- Too many properties. Each property you add multiplies the number of states that must be checked. Add a property only when at least two rules read it.
- Rules at different scales. A rule that works on single tiles and a rule that works on whole armies rarely interact through shared state. If you want them to meet, create a variable both can read.
- Unintended strong combinations. General rules also combine in ways that help the player too much. A heal-over-time effect and a shield that triggers on damage can chain forever. This is not a flaw in orthogonality. It is the reason the exploit chapter exists.
Putting it together
A practical process for a small system is:
- List the nouns that exist (units, tiles, items) and the properties they carry.
- Write each rule as a function from a state snapshot to proposed changes.
- For each field, pick a merge policy.
- Run the rules in a random order many times and compare results. Differences show hidden coupling.
- Add one new thing as data only and check what it can now do. If it needs code, ask what general property is missing.
Exercise
A game has a rule "arrows deal 5 damage" and a rule "wooden shields block 3 damage". A designer adds this line: "if the attacker is an arrow and the target has a wooden shield, also remove the shield after the hit". Which orthogonality problem does this create, and how would you fix it so the rules stay independent?
Show answer
The new line makes the damage rule and the shield rule depend on each other, because one now names the other's content ("arrow", "wooden shield"). It is a special case for one pair. To fix it, give the shield a general property, such as durability, and add a general rule: "when a hit is blocked, reduce the blocking object's durability by the blocked amount, and remove the object at zero". This works for any weapon and any shield, so a new weapon or shield gets the behavior without code changes.
Exercise
Using the snapshot method from this chapter, a unit has hp 2 (maximum 10), is poisoned (-2) and has a "bleeding" effect (-1). Both rules read the same snapshot. What is the new hp, and why is clamping at zero done after summing and not after each rule?
Show answer
The total change is -3, so 2 + (-3) = -1, and clamping gives 0. Clamping after the sum means the result does not depend on which rule runs first. Clamping after each rule would also give 0 here, but with a mix of damage and healing it makes the outcome depend on order, as in the poison and regeneration example.
Exercise
You have six rules and your tests show that shuffling their order changes the final state in about one run of every ten. List two steps you would take to find and remove the coupling.
Show answer
First, find the pair of rules responsible: run the shuffle test with each pair of rules alone until the results differ. Second, check whether they write the same field while another reads it, and switch to snapshot reading with an explicit merge policy (sum, max, union or priority) for that field. Then run the shuffle test again to confirm the results no longer differ.