Sub topic 16
Seeds, Replays, and Reproducible Bugs
This chapter assumes you know what a pseudo-random number generator (PRNG) is from the previous chapter. It also assumes you can read short Python programs. Here you will use seeds to replay a match exactly, reproduce a bug from a player report, and avoid the mistakes that silently break reproducibility.
What a seed does
A PRNG is a deterministic function. It holds an internal state, and each draw returns a number and updates the state. The seed is the starting state. The same seed gives the same sequence of draws, on every run.
import random
a = random.Random(123)
b = random.Random(123)
print([a.randint(1, 6) for _ in range(5)] == [b.randint(1, 6) for _ in range(5)]) # TrueDifferent seeds give unrelated-looking sequences, so you get variety by choosing a new seed for each match. You get reproducibility by keeping the seed.
A game normally picks its seed once, from an unpredictable source, and then records it:
import random
seed = random.SystemRandom().randrange(2**32)
print(f"match seed: {seed}")
rng = random.Random(seed)SystemRandom reads from the operating system, so each match starts differently. Storing seed costs a few bytes and makes the whole match replayable.
Replays: store the seed and the inputs
A replay does not need a recording of every outcome. If the game is deterministic, two things are enough:
- The seed.
- The player inputs, in order.
Replaying means running the same game code with the same seed and feeding it the same inputs.
import random
def run_game(seed, inputs):
rng = random.Random(seed)
gold = 0
for action in inputs:
if action == "mine":
gold += rng.randint(1, 6)
elif action == "gamble":
gold += 10 if rng.random() < 0.3 else -3
return gold
replay = {"seed": 2024, "inputs": ["mine", "gamble", "mine", "gamble", "gamble"]}
first = run_game(**replay)
second = run_game(**replay)
print(first, second, first == second)The two runs always agree. A replay file is tiny compared with a video, and you can inspect it, fast-forward it, or run it with extra logging.
sequenceDiagramReplace nothing above; the actual diagram follows.
Reproducing a bug
"I got five misses in a row and then the boss glitched" is hard to act on. With a log it becomes a test case. The report needs:
- The seed.
- The inputs, or at least enough of them to reach the state.
- The game version, because changing the code can change how many draws happen and in what order.
Once you have these, you can write the bug as an automated test that runs the replay and checks the result. The bug stays fixed because the test fails if it returns.
What breaks determinism
Having a seed is not enough. Any other source of variation makes the replay diverge, and after one wrong draw every later draw is shifted. The usual causes are below.
| Cause | Why it breaks replays | Fix |
|---|---|---|
| One shared generator for everything | A cosmetic draw (particles, idle animation) consumes a number, so later loot rolls change | Use separate generators per system |
| Seeding from the clock inside game logic | Each run gets a new sequence | Seed once at match start and store it |
| Python's built-in `hash()` on strings | It is randomized per process, so seeds derived from it differ between runs | Derive seeds with `hashlib` |
| Iterating over a `set` of strings | Order can differ between processes | Sort first, or use a list |
| Frame-rate-dependent logic | Draws happen per frame, and frame counts differ between machines | Step the simulation at a fixed rate |
| Threads drawing from one generator | Draw order depends on scheduling | Draw on one thread, or give each thread its own generator |
| Library or language upgrades | Algorithms can change between versions | Record the version and pin dependencies |
On the last row: Python guarantees that random() returns the same sequence for a given seed across versions. It does not guarantee this for helpers such as randint, choice, or shuffle. For long-lived replay files, store the build version with the seed, or implement your own small generator whose algorithm you control.
Separate streams for separate systems
The most useful habit is to give each system its own generator, all derived from one master seed. Then adding a new random effect to the particle system does not change the loot sequence.
import hashlib
import random
def derive_seed(master_seed, label):
data = f"{master_seed}:{label}".encode("utf-8")
return int.from_bytes(hashlib.sha256(data).digest()[:8], "big")
class Streams:
def __init__(self, master_seed):
self.master_seed = master_seed
self.streams = {}
def get(self, label):
if label not in self.streams:
self.streams[label] = random.Random(derive_seed(self.master_seed, label))
return self.streams[label]
def loot_rolls(master_seed, extra_particle_draws):
streams = Streams(master_seed)
fx = streams.get("effects")
for _ in range(extra_particle_draws):
fx.random()
loot = streams.get("loot")
return [loot.randint(1, 100) for _ in range(5)]
print(loot_rolls(99, 0))
print(loot_rolls(99, 40))
print(loot_rolls(99, 0) == loot_rolls(99, 40)) # TrueThe effects stream was drawn from 0 times in one run and 40 times in the other. The loot results are identical. With a single shared generator, they would differ.
This also helps with fairness. If the loot stream is independent, a designer can tune visual effects without changing anyone's loot outcomes.
Exposing seeds: a design and security question
A seed that players can see or guess lets them predict outcomes. That is fine for a single-player roguelike, where sharing a "daily seed" is a feature. It is a problem for anything competitive or anything involving real value.
For shared seeds that players type in, such as a roguelike's run code, keep the seed short and display it clearly. Players then share runs, and designers can find strong or broken seeds from community reports.
Fast-forwarding to the moment of the bug
A long match may take minutes to replay. When the bug appears at step 4000, you can run the replay without rendering and stop at the step you care about.
import random
def run_until(seed, inputs, stop_at):
rng = random.Random(seed)
gold = 0
for step, action in enumerate(inputs):
if step == stop_at:
break
if action == "mine":
gold += rng.randint(1, 6)
else:
gold += 10 if rng.random() < 0.3 else -3
return gold, rng.getstate()
inputs = ["mine", "gamble"] * 50
gold, state = run_until(2024, inputs, stop_at=40)
print(gold)getstate() returns the generator's internal state, and setstate() restores it. Saving the state at checkpoints lets you jump close to a bug without replaying from the start. It is also how a save-game system can store "where the random sequence was" along with the player's progress.
Common mistakes
- Logging the outcome but not the seed. You can see what happened but cannot rerun it.
- Seeding inside a function called every turn. Each call restarts the sequence, so a player sees the same "random" result repeatedly.
- Reseeding on load. If loading a save reseeds from the clock, a player can reload until they get a good roll. Restore the saved state instead, or accept this as a design choice.
- Testing only with one seed. A fix that works for seed 7 may fail for seed 8. Run many seeds, as the simulation chapter shows.
Exercise
A player reports that a chest gave bad loot three times in a row. You have their seed, but the replay does not reproduce the same loot. Name two likely causes.
Show answer
Two likely causes are (1) the player ran a different game build, so the order or number of random draws changed, and (2) some other system, such as particle effects, shares the loot generator and consumed draws that the replay did not repeat, or the inputs in the log are incomplete so the draws happened in a different order. Fixes are to record the build version with the seed, and to give loot its own generator derived from the master seed.
Exercise
Why is hash("loot") a poor way to derive a sub-seed in Python, and what should you use instead?
Show answer
Python randomizes string hashing per process, so hash("loot") returns different values on different runs and the derived seed will not be reproducible. Use a stable hash such as SHA-256 from hashlib, as in derive_seed above.