Simulations and seeded randomness

Games, models and tests often need randomness, and then need to run exactly the same way again: to reproduce a bug, to compare two versions, or to write a test. Cresset gives you two kinds of randomness for two jobs.

random(), randint(), shuffle(), choice()rng(seed)
Where the randomness comes fromThe real worldThe seed you choose
Needs a permissionYes: randomNo (it is just arithmetic)
Same run twiceOnly by recording and replayingAlways, from the seed alone
Use it forAnything that should be unpredictableSimulations, tests, procedural worlds

A generator with a seed

rng(seed) makes a random generator. The same seed gives the same numbers, on every machine, in every version of Cresset.

fn main() needs print:
    dice = rng(2026)
    rolls = range(5).map(i -> dice.int(1, 6))
    print(rolls)
    again = rng(2026)
    print(range(5).map(i -> again.int(1, 6)) == rolls)

The second line prints true: a new generator with the same seed repeats the same five rolls. A seed can be a number or a piece of text (rng("level 3")).

What a generator can do

MethodGives back
next()A number from 0 up to (not including) 1
int(low, high)A whole number from low to high, both included
chance(p)true with probability p (0 never, 1 always)
pick(list)A random item (the list must not be empty)
shuffle(list)A new list in random order (your list is not changed)
fork()A new, independent generator

Each call moves the generator forward, so a run is one fixed sequence. Pass the generator to functions as a value (fn roll(r: rng) -> num). Use fork() to give a part of your program its own stream, so adding a random choice in one place doesn't change the numbers used somewhere else.

A whole simulation

examples/hunt.crs plays out a small chase with records, an enum, match and one seeded generator. Every seed tells a different story, and the same seed tells the same story again:

seed 1: the killer wins at tick 29
seed 3: the survivors escape at tick 19
same seed, same story: true

Run it in the playground (the "Seeded simulation" example) and change a seed.

Why this matters

Mistakes it catches

A generator is its own type, so mixing it up with a number is caught before the program runs:

fn main() needs print:
    r = rng(1)
    print(r + 1)

Limits