Sub topic 17
Testing your design with simulation
Probability formulas answer simple questions. Real game systems add caps, pity counters, rerolls and player choices, and a formula for those gets hard to write or to trust. A simulation plays the system many times in code and measures what happens. This chapter covers how to build one and how to read its results. It also covers the mistakes that make simulation results misleading.
This chapter assumes you know expected value and variance from the earlier chapters. It also assumes you can read Python and know that a seeded generator repeats its sequence.
What a simulation tells you
A simulation, in the Monte Carlo sense, repeats a random process many times and summarizes the results. For a designer it answers three kinds of question:
- Average: How many packs does a player open per rare card, on average?
- Spread and tail: How bad is the unluckiest 1% of players?
- Comparison: Does design B reduce bad streaks compared with design A, and by how much?
The average is the expected value you can often compute by hand. The tail and the comparison are where simulation pays off, because streak length and worst-case waits are hard to derive when a system has several moving parts.
A first simulation: a pity timer
Take the pity timer from the earlier chapter. Each attempt has a 2% chance of success, and attempt 50 is guaranteed. Without a cap the average wait is 1 / 0.02 = 50 attempts. The cap should lower that average and, more importantly, cut the long tail. The code below measures both.
import random
from statistics import mean, pstdev
def attempts_until_drop(rng, base_chance, pity_limit):
attempts = 0
while True:
attempts += 1
if attempts >= pity_limit or rng.random() < base_chance:
return attempts
def simulate(pity_limit, base_chance=0.02, trials=20000, seed=11):
rng = random.Random(seed)
results = sorted(
attempts_until_drop(rng, base_chance, pity_limit) for _ in range(trials)
)
return {
"mean": round(mean(results), 1),
"stdev": round(pstdev(results), 1),
"p99": results[int(0.99 * trials)],
"worst": results[-1],
}
print("no pity ", simulate(float("inf")))
print("pity 50 ", simulate(50))
print("pity 30 ", simulate(30))Three details of this code are deliberate.
- The generator is created inside
simulatefrom a seed. Rerunning gives identical numbers, so you can compare two runs and know any difference comes from the design. - The results are sorted so you can read percentiles.
p99is the wait that 99% of players beat. Players tend to remember the worst waits, so this number often matters more than the mean. - The uncapped case uses
float("inf")as the limit, so one function covers both designs.
Expect the uncapped mean near 50 with a standard deviation also near 50, and a worst case several hundred attempts long. With a cap of 50, the mean should fall near 31.8. The worst case can never exceed 50.
Check the simulation against math
When a formula exists, use it to check the simulation. For the capped timer, the expected attempts equal the sum of (1 − p)^k for k from 0 to 49, which is (1 − 0.98^50) / 0.02, or about 31.8. If your simulated mean is far from 31.8, the code has a bug. A simulation that matches the math in the simple case earns trust in the cases where you have no formula.
How many trials are enough
Every simulated number is itself a random sample, so it has error. The standard error of a mean is the standard deviation divided by the square root of the number of trials. For a measured probability, such as a win rate, the 95% margin is roughly 1.96 × √(p(1 − p) / n).
| Trials | Margin on a 50% win rate |
|---|---|
| 100 | about ±9.8 points |
| 1,000 | about ±3.1 points |
| 10,000 | about ±1.0 points |
| 100,000 | about ±0.3 points |
Cutting the margin in half takes four times as many trials. If two designs differ by one point, 1,000 trials each cannot tell them apart. Report the margin with the result:
import math
from statistics import mean, stdev
def mean_with_margin(samples):
m = mean(samples)
margin = 1.96 * stdev(samples) / math.sqrt(len(samples))
return m, margin
rng = random.Random(5)
samples = [attempts_until_drop(rng, 0.02, 50) for _ in range(20000)]
m, margin = mean_with_margin(samples)
print(f"mean {m:.2f} +/- {margin:.2f}")The code reuses the imports and attempts_until_drop from the first listing. The printed interval should contain 31.8.
Test rules, not only averages
A simulation can also check that a rule always holds. These checks catch bugs that an average hides. They run as ordinary unit tests, and the seed keeps them from being flaky:
import random
def attempts_until_drop(rng, base_chance, pity_limit):
attempts = 0
while True:
attempts += 1
if attempts >= pity_limit or rng.random() < base_chance:
return attempts
def test_pity_cap_is_never_exceeded():
rng = random.Random(99)
for _ in range(50000):
assert attempts_until_drop(rng, 0.02, 50) <= 50
def test_cap_lowers_the_average():
rng = random.Random(99)
capped = [attempts_until_drop(rng, 0.02, 50) for _ in range(20000)]
uncapped = [attempts_until_drop(rng, 0.02, 10**9) for _ in range(20000)]
assert sum(capped) / len(capped) < sum(uncapped) / len(uncapped)
test_pity_cap_is_never_exceeded()
test_cap_lowers_the_average()
print("all checks passed")The first test states a guarantee and holds for every trial. The second states a comparison that is true by a wide margin, so a fixed seed makes it reliable. Do not write a test that asserts an exact random result, such as "the mean is 31.8". It will fail on a good implementation.
Common errors
| Error | What goes wrong | Fix |
|---|---|---|
| Too few trials | The result is noise and looks like a finding. | Compute the margin and raise the trial count until it is smaller than the difference you care about. |
| No seed | You cannot reproduce a surprising run. | Create `random.Random(seed)` in each experiment and log the seed. |
| One shared generator for all variants | Changing variant A changes the random numbers variant B sees. | Give each variant its own generator with the same seed. |
| Looking only at the mean | A design with a good average can still have a brutal tail. | Report a percentile such as p99 and the worst case. |
| Simulating a model of the game, not the game | The code differs from the shipped rules. | Call the real game function from the simulation. |
| Modeling players as random | Real players choose, so skill changes outcomes. | Add simple policies, such as "always take the safe option", and compare them. |
Comparing designs fairly
When you compare two variants, use the same seed for both and the same number of trials. Using identical random streams removes some noise from the comparison. Change one rule at a time, or you will not know which change caused the difference. Then ask a design question about the numbers, not a statistics question. For example: does lowering the cap from 50 to 30 cut the p99 wait enough to justify a faster reward rate? The simulation supplies the numbers. The design goal supplies the answer.
Exercise
A simulation of 1,000 matches shows Design A with a 54% win rate for the stronger player and Design B with 56%. A designer concludes that B rewards skill more. What is wrong with this conclusion, and what would you do?
Show answer
With 1,000 trials the margin on each win rate is about ±3 points, so the 2-point gap is within noise. Raise the trials to 100,000 per design, which shrinks the margin to about ±0.3 points. Give each design its own generator with the same seed and rerun. Only conclude that B rewards skill more if the gap stays larger than the margin.
Exercise
Modify attempts_until_drop so that every failed attempt raises the success chance by 0.5 percentage points, and the chance resets after a success. Which two numbers would you report to judge whether this soft pity beats the hard cap of 50, and why?
Show answer
Report the mean wait and a tail measure such as p99 or the worst case, each with a margin from enough trials. The mean shows the average cost to the player. The tail shows the worst experience, which is what the pity system is meant to limit. A design that matches the hard cap's mean but has a longer tail has not improved the worst case.