Sub topic 3
Local interaction and shared state
What this chapter assumes
You should be comfortable with loops, functions, lists, dictionaries and sets in Python. You should also know the idea of a game loop, where state is updated in discrete ticks or turns. The previous chapters defined emergence and argued for building games from small, general rules. This chapter looks at the mechanism that lets those rules affect each other: they read and write the same state, and each one only looks at a small piece of it.
Local rules, global patterns
A rule is local if its result depends only on information near the thing it acts on. "A grass tile catches fire if an adjacent tile is burning" is local. "A grass tile catches fire if more than 30% of the map is burning" is global, because it needs a count over the whole world.
Local rules matter for emergence because they remove any central coordinator. No rule knows what the whole board looks like, so no rule can aim at a global outcome. A fire front, a traffic jam, or a faction border has to come from many local decisions adding up. The designer can't write the front or the jam into the code, which is why they count as emergent.
Locality also gives you a propagation speed limit. If a rule reads only adjacent cells, information moves at most one cell per tick. This is a design tool as well as a technical fact. Fire that spreads one tile per tick gives the player time to react. Fire that spreads instantly across the map doesn't.
Shared state is the medium
Objects in an emergent system rarely call each other. Instead, they interact through shared state: data that more than one rule can read or write. A burning tile does not tell its neighbor to ignite. It changes its own tile, and the neighbor's rule notices.
This indirection (often called stigmergy, coordination through changes to the environment) has three practical effects:
- Rules written at different times, or by different people, can combine without knowing about each other.
- Adding a new rule that reads existing state can create new interactions with no change to the old rules.
- The state itself, not the rules, becomes the thing you inspect when something surprising happens.
Here is the same idea in a typical game. A guard AI reads a "noise" value in the tiles near it. A footstep rule writes noise to the tile under the player. A door rule increases noise when a door is slammed. None of these three rules mentions another. A player who slams a door to lure a guard away has found an interaction nobody scripted.
Choosing a neighborhood
The neighborhood is the set of places a rule is allowed to look. Your choice shapes the patterns that appear.
| Neighborhood | Cells read | Typical use | Side effect |
|---|---|---|---|
| Von Neumann | 4 orthogonal neighbors | Fire, flooding, tile-based puzzles | Spread forms diamond shapes |
| Moore | 8 neighbors including diagonals | Conway's Game of Life, crowd models | Spread forms squares |
| Radius r | All cells within distance r | Sound, line of sight, area effects | Faster propagation, more reads per tick |
| Graph edges | Nodes linked by roads, wires, or pipes | Strategy maps, networks, power grids | Shape follows the map, not a grid |
Moving from four neighbors to eight changes the shape of every fire and every flood, even though you wrote the same sentence of rule. Test a new neighborhood visually before you build on it.
Grids need a decision at the edges too. You can treat out-of-bounds as empty, treat it as a wall, or wrap around so the left edge touches the right edge (a torus). Each choice is a rule. Wrapping lets a fire leave one side of the map and re-enter on the other, which may be a surprise you don't want.
Update order decides the outcome
When a rule changes shared state while other cells are still being processed, the order of processing leaks into the result. Two designs exist:
- Synchronous update. Every rule reads the state as it was at the start of the tick. Changes go into a separate buffer, and the buffer becomes the new state when the tick ends.
- In-place (sequential) update. Rules write directly to the state while later rules are still reading it.
The code below applies the same rule both ways: grass next to fire becomes fire.
def neighbors(i, n):
return [j for j in (i - 1, i + 1) if 0 <= j < n]
def burning_neighbor(row, i):
return any(row[j] == "fire" for j in neighbors(i, len(row)))
def step_synchronous(row):
"""Read only the old row, write only the new one."""
new = row[:]
for i in range(len(row)):
if row[i] == "grass" and burning_neighbor(row, i):
new[i] = "fire"
return new
def step_in_place(row):
"""Write into the same row we are still reading."""
row = row[:] # copy so the caller's list is untouched
for i in range(len(row)):
if row[i] == "grass" and burning_neighbor(row, i):
row[i] = "fire"
return row
start = ["fire", "grass", "grass", "grass"]
print(step_synchronous(start)) # ['fire', 'fire', 'grass', 'grass']
print(step_in_place(start)) # ['fire', 'fire', 'fire', 'fire']
def ticks_to_reach(length, target):
row = ["fire"] + ["grass"] * (length - 1)
ticks = 0
while row[target] != "fire":
row = step_synchronous(row)
ticks += 1
return ticks
print(ticks_to_reach(10, 6)) # 6: one cell per tickThe in-place version burns the whole row in one tick because each newly lit cell is immediately visible to the cell on its right. That breaks the one-cell-per-tick limit. Worse, the speed depends on scan direction: sweeping right to left over the same row would light only one cell. The direction of your for loop has become a hidden game rule.
When two rules want the same cell
Synchronous updates solve read order but not write conflicts. If two units choose to move into the same tile in the same tick, both decisions were valid against the snapshot, and only one can win.
The standard pattern is to collect intents first and resolve them in a separate step:
def resolve_moves(intents):
"""intents maps unit_id -> target cell.
The lowest unit id wins a contested cell; losers stay where they are."""
winners = {}
for unit in sorted(intents):
cell = intents[unit]
winners.setdefault(cell, unit)
return {unit: cell for cell, unit in winners.items()}
moves = {3: (1, 1), 1: (1, 1), 2: (0, 0)}
print(resolve_moves(moves)) # {1: (1, 1), 2: (0, 0)}Unit 3 loses and stays put. This tie-break is deterministic, which makes bugs reproducible, but it is biased: low ids always win. If that bias would show up in play, break ties with a random number generator that you seed, or with a game-meaningful rule such as "the faster unit wins." The tie-break is a rule like any other, and players will find its consequences.
Where locality leaks
A system can claim to be local and still contain global reads. Watch for these:
- Global flags.
if enemies_alive == 0inside an enemy's behavior couples every enemy to the whole level. - Global counters used as triggers. "After 50 kills, spawn the boss" is a scripted event, not an interaction between rules. It may be the right choice, but it won't produce emergence.
- Hidden state. A cooldown timer stored on an object but invisible to other rules cannot take part in interactions. If a rule should react to it, put it where other rules can read it.
- Cached values. A cached "nearest enemy" that updates only every few seconds can let two rules disagree about what the world looks like.
- Order-dependent systems. Any place where swapping two
forloops changes the outcome is a leak, as the fire example showed.
A useful test: take any rule and ask what it reads and what it writes. If you can list those cells in one sentence, the rule is local. If you can't, look for a leak.
Design consequences
Locality and shared state are not goals in themselves. They are the constraints that make interactions predictable enough to design and open-ended enough to surprise you. A few working habits follow:
- Write each rule as a read set and a write set. For example: reads the four neighbors' types, writes its own type. Two rules interact exactly where one's write set overlaps another's read set.
- Store state in the world, not in the actor. If "wet" is a property of a tile or entity, a fire rule, a lightning rule and a movement rule can all use it.
- Prefer snapshots for anything that spreads. Use in-place updates only when you want order to matter.
- Treat edge handling and tie-breaks as rules. Document them, because players will probe them.
- Make the speed limit deliberate. If information moves one cell per tick, tune tick rate and map size with that in mind.
The next chapter takes these ideas to their cleanest form, a grid where every cell follows the same two-line rule.
Exercise
In the fire example, step_in_place is run on ["fire", "grass", "grass", "grass"] but the loop is changed to scan from the last index to the first (range(len(row) - 1, -1, -1)). What is the result after one call, and what does it show about update order?
Show answer
The result is ['fire', 'fire', 'grass', 'grass']. Scanning right to left, cells 3 and 2 are checked first, and neither has a burning neighbor yet. Cell 1 then sees the fire at cell 0 and ignites. Cell 0 is not grass, so it is skipped. The scan direction changed the outcome from a fully burned row to one new fire, which shows that in-place updates make iteration order part of the game's rules. A synchronous update gives the right-to-left answer in both directions.
Exercise
A designer wants "a guard becomes alert if any other guard on the level is alert." Is this a local rule? Rewrite it so it is, and name one gameplay effect of the change.
Show answer
It is not local, because each guard reads the alert state of every other guard on the map. A local version is "a guard becomes alert if an alert guard is within 8 tiles, or if it hears noise in its own tile." Alertness then spreads from guard to guard at a limited speed, so the player can slip away before the alarm reaches distant guards, and an isolated guard can be dealt with quietly. The global version would put the whole level on alert at once.