Worlds, AI and multiplayer · 5 MIN READ
Reproducible worlds: one seed, one random stream per system, and no global rand
Generate a seeded cave with a math/rand/v2 PCG source, keep each system on its own derived stream and explain why global or shared randomness breaks replays.
Procedural generation is only useful when the same seed builds the same world: a player shares a seed, a tester attaches one to a bug report, a replay regenerates the level instead of storing it. That property is not automatic. It depends on who owns each random generator, how many values each system draws and in what order, and whether any code path reaches for a generator nobody seeded.
gamedev · A MAP OF THE IDEA
- Derive stream per system
- Draw in fixed order
- Smooth into second grid
- Validate and fingerprint
Useful when
- A 64-bit seed rebuilds the whole level anywhere.
- Named streams let systems change without reshuffling others.
Watch out
- Map iteration, goroutines or global rand silently break replays.
- Floating-point results can differ across architectures through FMA.
Implementation & operation cost: A few generator constructors and a validation pass; the lasting cost is keeping old generator versions alive while saved seeds depend on them.
A seed replaces the content you did not store
A seeded generator is a pure function of its seed and of the sequence of calls made on it. Store a 64-bit seed and a generator version and you can rebuild a whole cave on load, on a server or on a teammate's machine. The contract breaks in three ways: a different seed, which is obvious; different code, such as a tuned constant or a new pass; or a different number or order of draws from the same stream, which is subtle and the usual bug. The last one is why each system needs its own generator. In math/rand/v2, rand.New(rand.NewPCG(seed1, seed2)) returns a *rand.Rand over a PCG source with 128 bits of state, and nothing else in the process can draw from it unless you hand it over.
A cellular-automaton cave from a named stream
The program derives a terrain stream from a world seed and the name "terrain", fills a 36x12 grid with 45 percent walls and runs four smoothing passes in which a cell becomes wall when at least five of the nine cells in its 3x3 block are walls. It prints the cave, counts floor regions, regenerates with the same seed, tries the next seed, and then shows what a single extra loot roll does to a shared stream compared with separate streams.
package main
import (
"fmt"
"hash/fnv"
"math/rand/v2"
"strings"
)
const w, h = 36, 12
// stream derives an independent generator for one named system.
// The world seed picks the world; the name picks the system's stream.
func stream(worldSeed uint64, name string) *rand.Rand {
f := fnv.New64a()
f.Write([]byte(name))
return rand.New(rand.NewPCG(worldSeed, f.Sum64()))
}
// Cave runs a cellular automaton: random fill, then smoothing passes.
func Cave(r *rand.Rand) []bool {
walls := make([]bool, w*h)
for i := range walls {
walls[i] = r.IntN(100) < 45
}
next := make([]bool, w*h)
for range 4 {
for y := range h {
for x := range w {
edge := x == 0 || y == 0 || x == w-1 || y == h-1
next[y*w+x] = edge || wallsAround(walls, x, y) >= 5
}
}
walls, next = next, walls // double buffer: never read a half-updated grid
}
return walls
}
// wallsAround counts walls in the 3x3 block; the border counts as wall.
func wallsAround(walls []bool, cx, cy int) int {
n := 0
for y := cy - 1; y <= cy+1; y++ {
for x := cx - 1; x <= cx+1; x++ {
if x < 0 || y < 0 || x >= w || y >= h || walls[y*w+x] {
n++
}
}
}
return n
}
func Render(walls []bool) string {
var b strings.Builder
for y := range h {
for x := range w {
if walls[y*w+x] {
b.WriteByte('#')
} else {
b.WriteByte('.')
}
}
b.WriteByte('\n')
}
return b.String()
}
// Regions counts connected floor areas with an explicit-stack flood fill.
func Regions(walls []bool) (count, largest int) {
seen := make([]bool, len(walls))
for start := range walls {
if walls[start] || seen[start] {
continue
}
count++
size, stack := 0, []int{start}
seen[start] = true
for len(stack) > 0 {
i := stack[len(stack)-1]
stack = stack[:len(stack)-1]
size++
for _, d := range [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
x, y := i%w+d[0], i/w+d[1]
if x < 0 || y < 0 || x >= w || y >= h {
continue
}
if n := y*w + x; !walls[n] && !seen[n] {
seen[n] = true
stack = append(stack, n)
}
}
}
largest = max(largest, size)
}
return count, largest
}
func fingerprint(s string) uint64 {
f := fnv.New64a()
f.Write([]byte(s))
return f.Sum64()
}
func main() {
const seed = 20261118
cave := Cave(stream(seed, "terrain"))
first := Render(cave)
fmt.Print(first)
regions, largest := Regions(cave)
fmt.Printf("floor regions: %d, largest: %d cells\n", regions, largest)
again := Render(Cave(stream(seed, "terrain")))
fmt.Printf("same seed, same map: %t (%016x)\n", again == first, fingerprint(first))
other := Render(Cave(stream(seed+1, "terrain")))
fmt.Printf("next seed, different map: %t (%016x)\n", other != first, fingerprint(other))
// Shared stream: a new loot roll before generation shifts every later draw.
shared := rand.New(rand.NewPCG(seed, 0))
before := Render(Cave(shared))
shared = rand.New(rand.NewPCG(seed, 0))
_ = shared.IntN(6) // the loot system now rolls first
after := Render(Cave(shared))
fmt.Printf("shared stream, map survives a new loot roll: %t\n", before == after)
// Separate streams: the loot roll consumes only the loot stream.
loot := stream(seed, "loot")
_ = loot.IntN(6)
isolated := Render(Cave(stream(seed, "terrain")))
fmt.Printf("separate streams, map survives a new loot roll: %t\n", isolated == first)
}stream hashes the system name with FNV-1a into seed2, so "terrain" and "loot" get unrelated sequences from one world seed and adding a system never requires renumbering the others. Cave draws exactly one IntN per cell in row-major order, then smooths into a second buffer and swaps the two. Reading and writing one grid would let already-updated cells bias their neighbors, and the result would depend on scan direction. Border cells are forced to wall so the cave is closed. Regions flood-fills floor cells with an explicit stack and finds 2 regions, the main cave and a sealed pocket on the left, which the last section deals with. The fingerprints are FNV hashes of the printed map, handy as golden values in tests. One IntN(6) before generation on a shared stream changes the whole map; on separate streams it changes nothing.
Why global and shared randomness break replays
The top-level functions in math/rand/v2, such as rand.IntN, draw from a process-wide source that is seeded randomly at startup and has no Seed function, so a map built with them can never be rebuilt. A seedable shared generator fails in the way the shared-stream line shows: any new call anywhere, from a particle effect, a library or a debug overlay, shifts every value drawn after it. Concurrency makes it worse. A *rand.Rand is not safe for concurrent use, and even behind a mutex, which goroutine draws next depends on the scheduler, so the world changes from run to run. The rule is ownership: each system or chunk gets its own *rand.Rand, passed explicitly as a parameter or held in a field and used by one goroutine. Name streams after what they generate, such as terrain, loot, enemies and weather, and derive them all from the single world seed the player sees.
Rules that keep generation reproducible
Draw the same number of values in the same order on every run: loop over slices and fixed coordinate ranges, never over a map, whose iteration order Go randomizes on purpose. For streamed or endless worlds, derive a stream per chunk from the world seed and the chunk coordinates, so chunk (12, -3) is identical whether the player reaches it first or last. Prefer integer rules like the automaton above. Floating-point noise is reproducible on one platform, but the Go specification allows fused multiply-add, which compilers use on architectures such as arm64, so an arm64 client and an amd64 server can differ in the last bits; when generation must match bit for bit, use integer or fixed-point math or force rounding with explicit float64 conversions. Store a generator version beside the seed and keep old generators while saves reference them. The PCG source implements MarshalBinary and UnmarshalBinary, so a mid-run generator state can go into a save file. Finally, PCG itself is a fixed algorithm, but helpers such as IntN are library code; golden fingerprints in tests tell you at upgrade time whether a toolchain change altered any world.
Validate the world before the player sees it
A random fill does not promise a playable level. The cave printed above has two regions, and a player spawned in the small pocket is trapped. Make validation part of generation: flood-fill from the spawn point, fill unreachable pockets with wall or carve a tunnel to them, require a minimum floor area and confirm that the exit is reachable with the pathfinding code from the previous lesson. When a candidate fails, retry deterministically by deriving the next attempt from the seed and the attempt number, and cap the attempts so a pathological seed fails loudly instead of looping. Test with a few thousand seeds in CI: assert the invariants on each one, record the fingerprints of a handful as golden values, and keep every seed that ever produced a broken map as a permanent regression fixture.
TAKE THIS WITH YOU
Give every generating system its own seeded *rand.Rand derived from the world seed, never draw from global or shared generators in generation code, and validate and fingerprint the result so a seed stays a reliable save format.
Check your understanding
A designer adds one loot roll at level start, and every seeded cave changes shape. Which design prevents this?
Go to the source
Progress stays in this browser. No account needed.