Sub topic 11
Simulating a loop in code
This chapter assumes you can read short Python functions and the percent-growth formulas from the earlier chapters on reinforcing and balancing loops. You will turn a loop into a small program, run it, and read the numbers it produces.
Why simulate a loop
A causal loop diagram tells you which way a loop pushes. It does not tell you how fast, or what happens when two loops push against each other. A simulation gives you numbers for those questions. You can change one parameter, rerun it, and see the effect in seconds, long before you build a prototype or recruit playtesters.
Every simulation in this chapter has the same four parts:
- State: the stocks, such as gold, health or score.
- Update rule: how the flows change the stocks in one step.
- Step loop: apply the rule once per turn, round or tick.
- History: store the state after each step so you can inspect it.
The shape of this program is itself a feedback loop. Each step reads the state that the previous step wrote. A loop in your game becomes a loop in your code.
A reinforcing loop
In a reinforcing loop, the flow depends on the stock. Here income is 10% of the gold you already hold.
def reinforcing(turns, rate=0.10, start=10.0):
gold = start
history = [gold]
for _ in range(turns):
gold += rate * gold # income proportional to what you already have
history.append(gold)
return history
print([round(g, 2) for g in reinforcing(5)])This prints [10.0, 11.0, 12.1, 13.31, 14.64, 16.11]. The growth is geometric: each turn multiplies the stock by 1 + rate. The rounding is only for display. Floating-point arithmetic produces values such as 13.310000000000002, so round before you print or compare.
A balancing loop
In a balancing loop, the flow depends on the gap between the stock and a target.
def balancing(turns, target=100.0, strength=0.25, start=20.0):
health = start
history = [health]
for _ in range(turns):
health += strength * (target - health) # correction shrinks as the gap closes
history.append(health)
return history
print([round(h, 2) for h in balancing(5)])This prints [20.0, 40.0, 55.0, 66.25, 74.69, 81.02]. The first correction is 20 points and the second is 15. Each one is 75% of the previous. The stock approaches the target but never quite reaches it.
Measuring a loop
A printed list is hard to compare across runs. Pull out a few numbers that you can put next to each other.
def first_turn_at_least(history, threshold):
"""Index of the first turn where the stock reaches threshold, or None."""
for turn, value in enumerate(history):
if value >= threshold:
return turn
return None
def reinforcing(turns, rate=0.10, start=10.0):
gold = start
history = [gold]
for _ in range(turns):
gold += rate * gold
history.append(gold)
return history
def balancing(turns, target=100.0, strength=0.25, start=20.0):
health = start
history = [health]
for _ in range(turns):
health += strength * (target - health)
history.append(health)
return history
print(first_turn_at_least(reinforcing(60), 100)) # 25
print(first_turn_at_least(balancing(60), 95)) # 10The reinforcing loop needs 25 turns to grow from 10 to 100. The balancing loop needs 10 turns to get within 5 points of its target. Good metrics for a loop usually include:
| Metric | What it tells you | Typical loop type |
|---|---|---|
| Turns to reach a threshold | Pacing: how long a phase lasts | Both |
| Final value after N turns | Where the stock ends up | Both |
| Gap between players over time | Whether leads grow or shrink | Both |
| Number of times the leader changes | Tension and comeback potential | Balancing |
Two loops, one race
The next example combines both loop types. Player A starts 2 points ahead. Each round, every player grows by 10% of their own score (reinforcing). Each player also gains catch_up times their distance from the leader (balancing).
def final_gap(rounds, catch_up):
scores = [12.0, 10.0] # player A leads by 2
for _ in range(rounds):
lead = max(scores)
# reinforcing growth of 10% plus a balancing bonus proportional to distance behind the leader
scores = [s + 0.10 * s + catch_up * (lead - s) for s in scores]
return scores[0] - scores[1]
for c in (0.0, 0.1, 0.3):
print(c, round(final_gap(10, c), 2))The output is:
0.0 5.19
0.1 2.0
0.3 0.21You can predict these numbers without running the code. The leader's catch-up bonus is zero, because the leader is at the lead. The follower gets a bonus. When you subtract the two scores, the gap changes each round by this factor:
new_gap = (1.10 - catch_up) * old_gap- At
catch_up = 0.0the factor is 1.10, and 2 × 1.1¹⁰ ≈ 5.19. - At
catch_up = 0.1the factor is exactly 1.0, so the gap stays at 2. The two loops cancel. - At
catch_up = 0.3the factor is 0.8, and 2 × 0.8¹⁰ ≈ 0.21.
The result also shows what "loop dominance" means in numbers. The reinforcing loop is worth 10% and the balancing loop is worth catch_up. Whichever is larger controls whether the gap grows or shrinks.
Edge cases that break a simulation
Overshoot
The balancing update x += strength * (target - x) is only well behaved when strength is between 0 and 1. A strength of 1 jumps straight to the target. Above 1, the correction is larger than the gap, so the stock passes the target.
def balancing(turns, target=100.0, strength=0.25, start=20.0):
health = start
history = [health]
for _ in range(turns):
health += strength * (target - health)
history.append(health)
return history
print(balancing(5, strength=1.5)) # [20.0, 140.0, 80.0, 110.0, 95.0, 102.5]
print([round(h) for h in balancing(5, strength=2.5)])At 1.5 the stock swings around the target with the swing halving each turn. At 2.5 each swing is 1.5 times larger than the last, so the stock moves away from the target with growing swings. Nothing in your game's logic changed. Only the correction strength did. Real games hit the same problem when a correction arrives late or is too strong, and the Delays and oscillation chapter covers it.
Order of updates
In final_gap, lead is computed once before anyone updates. This is a simultaneous update. If you recomputed the leader after updating player A, player B would react to a score that already includes A's gain. That is a different game. Decide which behavior you want, then write the code to match it.
Caps and negative values
A real stock has limits: health cannot exceed its maximum, and gold cannot go below zero. Add them explicitly with min and max. An unclamped reinforcing loop eventually produces numbers no game could display. The Limits, caps and saturation chapter covers how these limits change a loop's behavior.
Time step size
One update per turn is natural for turn-based games. For real-time games the same rule runs every frame, so scale the rate by the frame time (rate * dt). Otherwise the loop runs faster on a faster machine.
A workflow for tuning
- Write the update rule for one loop and check it against a hand calculation.
- Add one parameter at a time, and sweep it across a small range of values as the
for c in (...)loop does above. - Record a metric per run, such as final gap or turns to threshold.
- Look for the value where behavior changes. Here it is
catch_up = 0.1. - Pick a value on the side you want, and keep a margin from the edge.
Exercise
In final_gap, change the reinforcing rate from 0.10 to 0.20 and keep the starting scores. Using the gap-factor reasoning from this chapter, what value of catch_up keeps the gap constant at 2?
Show answer
The gap factor is (1 + rate) - catchup. With rate 0.20 the factor is 1.20 - catchup, which equals 1.0 when catch_up = 0.2. A stronger reinforcing loop needs a stronger balancing loop to cancel it.
Exercise
You run balancing(20, strength=2.5) and the health values swing wider every turn. Which line of the update rule causes this, and what range of strength avoids it?
Show answer
The line health += strength * (target - health) causes it. When strength is above 1, each correction is bigger than the gap, so the stock overshoots the target. Above 2, each overshoot is larger than the one before, so the swings grow. Values between 0 and 1 approach the target without crossing it. Values between 1 and 2 cross it but settle.