Sub topic 15
Pseudo-random number generators
This chapter assumes you can read simple Python and know the ideas from earlier chapters: probabilities, weighted tables, and why short runs of random results feel streaky. Here you will see where the random numbers behind those tools come from, and which implementation mistakes can quietly distort a design.
What a PRNG is
A computer is deterministic, so it cannot produce randomness out of nothing. Games use a pseudo-random number generator (PRNG). This is a small algorithm that holds an internal state (a number or block of numbers) and updates it on every call. Each call has two steps:
- Apply a fixed transition function to the state, producing a new state.
- Apply an output function to the new state, producing the number you receive.
If you know the algorithm and the current state, every future number is determined. The output only looks random: it passes statistical tests for even spread and lack of obvious patterns.
Two properties follow from this design.
- The sequence repeats eventually. The state can only take a finite number of values. The number of calls before the sequence cycles is the period. Modern generators have periods so long that a game will never reach them.
- The same starting state gives the same sequence. This is a feature. Later chapters use it for replays and reproducible bugs.
A tiny generator you can read
The simplest classic design is the linear congruential generator (LCG). Its state is one integer, and the transition is a multiply, an add, and a remainder.
class LCG:
"""32-bit linear congruential generator (Numerical Recipes constants)."""
def __init__(self, seed):
self.state = seed % 2**32
def next_u32(self):
self.state = (1664525 * self.state + 1013904223) % 2**32
return self.state
def random(self):
# Float in [0, 1), like random.random()
return self.next_u32() / 2**32
gen = LCG(1)
print([round(gen.random(), 3) for _ in range(3)])
print([gen.next_u32() & 1 for _ in range(8)])The floats look fine. The second line prints [0, 1, 0, 1, 0, 1, 0, 1] for the lowest bit, which is not random at all. In this LCG the lowest bit simply alternates, and the higher bits are better than the lower ones. A naive rule such as "even number means the attack crits" would produce a perfect alternating pattern. An LCG is fine for learning but weak for production. Use the generator from your engine or language, and take randomness from the whole number rather than from its low bits.
Generators you will actually use
Python's random module uses the Mersenne Twister, which has a period of 2^19937 − 1. Many engines use newer small generators such as PCG or xoshiro, which are faster and use less state. For design work, the differences that matter are practical ones.
| Property | Why a designer cares |
|---|---|
| Statistical quality | Poor generators show patterns in low bits or in sequences of pairs, which can skew a weighted table. |
| State size | Small state is cheap to store per entity or save in a save file. Mersenne Twister needs about 2.5 KB. |
| Speed | Rarely matters for turn-based rules. It can matter for particles or procedural generation. |
| Predictability | A cheap generator can be predicted from a few outputs. That is a problem for anything with security or money at stake. |
Mistake 1: modulo bias
Generators produce a number in a fixed range, such as 0 to 255 or 0 to 2^32 − 1. To get a die roll, many programmers write value % 6. That is slightly unfair whenever the range does not divide evenly by 6.
from collections import Counter
counts = Counter(b % 6 for b in range(256))
print(sorted(counts.items()))
# [(0, 43), (1, 43), (2, 43), (3, 43), (4, 42), (5, 42)]Of the 256 byte values, faces 0 to 3 each get 43 and faces 4 and 5 each get 42. With a 32-bit source the skew is about one part in 700 million, so it is invisible. With a small source, such as one byte, a table with many entries, or a very large range, it becomes noticeable. The fix is rejection sampling: throw away values from the uneven tail and draw again.
import random
def unbiased_die(rng):
# 252 is the largest multiple of 6 that fits in a byte (0..255)
while True:
b = rng.randrange(256)
if b < 252:
return b % 6 + 1
rng = random.Random(5)
print([unbiased_die(rng) for _ in range(10)])In everyday Python, randint, randrange, choice, and choices already handle this, so prefer them over hand-rolled arithmetic. The lesson applies when you write code against a raw integer stream, as in some engines, shaders, and embedded scripting languages.
Mistake 2: one shared generator for everything
Suppose one generator drives loot drops, enemy AI, and visual effects. Adding one particle effect that draws a random number now shifts every later loot roll. That breaks replays and makes bugs impossible to reproduce. The usual practice is one generator per purpose, and each generator gets its own stream.
import random
def run(extra_draws, separate):
loot = random.Random(10)
fx = random.Random(11) if separate else loot
for _ in range(extra_draws):
fx.random() # cosmetic randomness, such as particles
return [loot.randint(1, 100) for _ in range(5)]
print(run(0, True) == run(5, True)) # True: loot is unaffected
print(run(0, False) == run(5, False)) # False in practice: loot shiftedA common split is a gameplay generator that determines outcomes and a cosmetic generator that determines visuals. Only the first needs to be saved, replayed, or synchronized between players. The same idea applies per system. A change to the number of random calls in combat should not change the dungeon layout.
Mistake 3: creating a new generator every call
Creating random.Random(seed) inside a function and drawing once returns the same first value each time if the seed is the same. This often happens when a developer seeds with something coarse, such as the current second. Create the generator once, keep it in your game state, and pass it where it is needed. The earlier examples in this tutorial do this by passing rng into functions such as open_pack and ShuffleBag.
Mistake 4: assuming the generator enforces fairness
A good PRNG gives you independent draws. Independent draws still produce streaks, because that is what independence means. A better generator does not make a loot table feel fairer. Shuffle bags and pity timers do that, and they are layered on top of whichever generator you use. Keep the two jobs separate:
- The PRNG supplies uniform numbers.
- Your design layer converts them into the distribution and guarantees the game needs.
Checklist
- Use the language or engine generator, not a hand-written one, unless you are learning.
- Create generators once and pass them around. Do not recreate them per call.
- Give separate systems separate generators.
- Use library range functions to avoid modulo bias.
- Use a cryptographic source only where security matters, and a seedable PRNG everywhere else.
Exercise
A designer writes roll = rng.getrandbits(8) % 100 + 1 to make a percentile roll. Which results are slightly more likely than the others, and how would you fix it?
Show answer
A byte has 256 values, and 256 = 2 × 100 + 56. Values 0 to 55 each occur three times and values 56 to 99 only twice. After % 100 + 1, rolls 1 to 56 are therefore about 50% more likely than rolls 57 to 100. The fix is either rng.randint(1, 100), which is already unbiased, or rejection sampling that discards bytes of 200 or above before taking the remainder.