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 from | The real world | The seed you choose |
| Needs a permission | Yes: random | No (it is just arithmetic) |
| Same run twice | Only by recording and replaying | Always, from the seed alone |
| Use it for | Anything that should be unpredictable | Simulations, 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
| Method | Gives 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
- Reproduce any run. Log the seed when something goes wrong, and you can replay exactly that run later.
- Real tests. A test can run a simulation with seed 42 and check the result, forever.
- Compare fairly. Run old and new rules against the same seeds to see what really changed.
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
- The generator is fast and repeatable, not secure. Never use it for passwords or tokens. Use
random()for those. - The numbers a seed produces are a promise: they won't change between versions, so recorded seeds stay valid.