Sub topic 2
Combining rules: orthogonal design
This chapter assumes you can write Python functions and use dictionaries and sets. You should also understand a game loop that updates state once per tick.
Orthogonal design means each rule handles one concern and does not depend on the others. You can change one rule without editing the rest. Orthogonal rules multiply. Three movement rules and four terrain rules produce twelve combinations, and you never write twelve special cases.
Building a tag-based interaction system
Give each object tags, such as flammable or wet, instead of naming objects in rules. A rule reads tags, not object names. The fire rule below has no water case. Water survives because it lacks the flammable tag.
FLAMMABLE = {"grass", "wood"}
NEIGHBORS = ((1, 0), (-1, 0), (0, 1), (0, -1))
def tick(grid):
"""One step: fire burns out and ignites flammable neighbors."""
h, w = len(grid), len(grid[0])
new = [row[:] for row in grid]
for y in range(h):
for x in range(w):
if grid[y][x] == "fire":
new[y][x] = "ash"
for dx, dy in NEIGHBORS:
nx, ny = x + dx, y + dy
if 0 <= nx < w and 0 <= ny < h and grid[ny][nx] in FLAMMABLE:
new[ny][nx] = "fire"
return new
grid = [["fire", "grass", "grass", "water", "grass"]]
for _ in range(3):
grid = tick(grid)
print(grid) # [['ash', 'ash', 'ash', 'water', 'grass']]> Note: Add a tag to a new object type, and every existing rule applies to it at once.
Feedback loops that shape a match
A feedback loop routes a result back into its own input. Positive feedback amplifies a lead. Negative feedback shrinks it. In the income function below, interest is positive feedback, because more gold earns more gold. catch_up is negative feedback, because a larger gap behind the leader earns more.
def income(gold, leader_gold, base=10, interest=0.05, catch_up=0.1):
return base + interest * gold + catch_up * (leader_gold - gold)
leader, trailer = 200, 100
print(income(leader, leader)) # 20.0
print(income(trailer, leader)) # 25.0Positive loops widen gaps over a match. Negative loops narrow them. Predict the effect of each term before you tune it.
Exercise:
Exercise
In the fire example, what happens to a grass tile that sits between two fire tiles on the same tick? Does it burn once or twice, and why does the result not depend on the order of the loop?
Show answer
It becomes fire once. Both fire neighbors write "fire" into the copy new, and the rule reads from grid, the previous state. Because every tile reads the old state and writes the new one, the update does not depend on loop order.