osrlib.core.rng
Where every random number in osrlib comes from: named, seeded, repeatable streams.
RngStreams is the entry point. Make one from a master
seed, the integer that every random number in a game comes from. Get a stream from it by
name with get, and pass that stream to the function
you call, like roll, the combat and treasure functions, or
character creation. A GameSession builds a
container from the seed you give it and passes the right stream to each rules function,
so in a game that uses a session you don't call this module yourself.
The members, in the order you use them:
RngStreams: takes a master seed and stores a game's streams.RngStreams.get: takes a stream name and returns theRngStreamfor it.StreamName: the stream names a session uses.RngStream.randbelow: takes a bound and returns a random number below it.rollcalls it for you.RngStreams.export_statesandRngStreams.restore_states: save every stream's position as anRngStreamState, and put the positions back.derive_init_pair: takes a seed and a name and returns the numbers that start the stream, for checking another implementation.
Each stream name has a separate sequence. Rolling a hundred treasure hoards doesn't
change the next attack roll. Adding a draw to one subsystem doesn't change the results of
any other subsystem, so you can replay a saved game and reproduce a bug.
StreamName lists every stream a running session draws
from, and each *_STREAM constant in the library is one of its members. Each member's
docstring and
the RNG streams reference
describe what that stream covers. Code you run without a session can use any name. Ask
for the same name again to get the same stream back. It continues from where it stopped instead
of starting the sequence over.
The same master seed and the same stream name give the same draws, in this release and
in every later one. The generator is PCG64, in the pcg_setseq_128_xsl_rr_64 form with
128 bits of state and a 64-bit output. numpy calls this generator PCG64, not
PCG64DXSM. Each next_uint64 advances the
state first and then takes the output from the new state, as the C reference
implementation does. A stream's starting numbers come from
SHA-256(master_seed_bytes + b":" + stream_key_utf8), with the master seed written as 16
bytes, most significant first. An implementation that differs in any of these steps
draws different numbers, so it can't replay an osrlib game.
osrlib never uses Python's random module, and streams are its only random number
generator. If you write a rule of your own to run beside osrlib's, take a stream as an
argument the same way.
Typical usage:
from osrlib.core.dice import roll
from osrlib.core.rng import RngStreams, StreamName
streams = RngStreams(master_seed=42)
# Each name is its own sequence, so one subsystem's draws never move another's.
attack = roll("1d20", streams.get(StreamName.COMBAT))
gold = roll("2d6×100", streams.get(StreamName.TREASURE))
assert attack.total == 14
assert gold.total == 600
# Same seed, same name, same draws.
assert roll("1d20", RngStreams(master_seed=42).get(StreamName.COMBAT)).total == 14
RngStream
One named sequence of random numbers, which you pass to any function that rolls.
Get one from RngStreams.get. For a single stream
with no container, as in a test, call
from_seed_material. Every function in
the kernel that rolls anything takes one of these, and streams are the only source of
randomness in the library.
Each draw advances the stream, so each call gets the next number in the sequence, and the
order of your calls is part of what the seed determines. Pass the stream itself, never a
copy. Draw with randbelow for a bounded
number, or call roll with a dice expression.
The constructor runs PCG64's standard initialization from an (initstate, initseq)
pair. derive_init_pair makes that pair from a
master seed and a name.
Examples:
from osrlib.core.rng import RngStreams
stream = RngStreams(master_seed=42).get("combat")
assert stream.randbelow(20) + 1 == 14
Start the stream from a PCG64 init pair.
The initialization is PCG's reference procedure: set the state to 0, set the increment to
(initseq << 1) | 1, step, add initstate, step, everything modulo 2**128. The top
bit of initseq has no effect, as in the reference implementation, so two values
that differ only in that bit start the same stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initstate
|
int
|
The 128-bit init state, from 0 up to but not including 2**128. |
required |
initseq
|
int
|
The 128-bit sequence selector, in the same range. Two streams with the same init state and different selectors draw different sequences. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If either argument is outside the allowed range. |
from_seed_material
classmethod
Build the named stream for a master seed, in one step.
Use this when you want a single stream and no container. When you want several,
use RngStreams instead, which stores each stream and
saves them all together.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
master_seed
|
int
|
The game's master seed, from 0 up to but not including 2**128. |
required |
key
|
str
|
The stream's name. |
required |
Returns:
| Type | Description |
|---|---|
RngStream
|
A stream at the start of its sequence. The same seed and name always give a stream that draws the same numbers. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
restore
classmethod
restore(snapshot: RngStreamState) -> RngStream
Rebuild a stream at the position saved in a snapshot.
Use it when you load a game you saved yourself.
load_game restores a session's streams for you.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot
|
RngStreamState
|
A position from
|
required |
Returns:
| Type | Description |
|---|---|
RngStream
|
A stream whose next draw is the one the saved stream would have made. |
Examples:
import json
from osrlib.core.rng import RngStream, RngStreams, RngStreamState
stream = RngStreams(master_seed=42).get("combat")
stream.randbelow(20)
saved = stream.export_state().model_dump_json()
# Later, read the position back from disk and draw on from it.
restored = RngStream.restore(RngStreamState.model_validate(json.loads(saved)))
assert restored.randbelow(20) + 1 == 11
export_state
export_state() -> RngStreamState
Record the stream's position, so you can come back to it.
Pass the result to restore to get a stream
at this position. To save all of a game's streams at once, call
RngStreams.export_states instead.
Exporting draws nothing and leaves the stream where it was.
Returns:
| Type | Description |
|---|---|
RngStreamState
|
The position. Write it to disk with |
Examples:
from osrlib.core.rng import RngStreams
stream = RngStreams(master_seed=42).get("combat")
stream.randbelow(20)
# Exporting twice gives the same record, because exporting draws nothing.
snapshot = stream.export_state()
assert stream.export_state() == snapshot
document = snapshot.model_dump()
assert sorted(document) == ["inc", "state"]
next_uint64
next_uint64() -> int
Draw the next raw 64-bit number from the stream.
This is the generator's raw output, with no bound applied. For a die or any
bounded value, call randbelow instead.
If you take a remainder of this number, the result is biased. Computing a bounded
value yourself also uses a different number of raw draws than osrlib does, so the
stream falls out of step with a replay.
The stream advances first and then produces the output from its new state, following the reference C implementation.
Returns:
| Type | Description |
|---|---|
int
|
A number from 0 up to but not including 2**64, each equally likely. |
Examples:
randbelow
Draw a number from 0 up to but not including n, each equally likely.
This is the bounded draw that the rest of osrlib uses. For a die, add 1:
stream.randbelow(6) + 1 is a d6. For a dice expression, call
roll instead and let it do the arithmetic.
How many raw numbers a single call consumes varies. The method takes the top bits
of a raw draw and discards the candidate if it's at or above n, which makes
every result equally likely. With a bound that's a power of two, the method never
discards a draw. With bounds of 3, 6, 10, 12, 20, and 100 it sometimes does, so a
stream's position after a roll depends on which values came up, not on how many
times you called. randbelow(1) returns 0 and still uses a draw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The bound, which the result stays below. Must be from 1 to 2**64, the range of one raw draw. |
required |
Returns:
| Type | Description |
|---|---|
int
|
A number from 0 up to but not including |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
RngStreamState
Bases: BaseModel
A stream's position in its sequence, as a frozen model you can write to disk.
RngStream.export_state returns one and
RngStream.restore takes it back, so a game
saved halfway through a dungeon resumes on the next draw instead of starting the
sequence over. save_game and
load_game do this for every stream a session has
used, so you handle these yourself only when you save a game without a session.
The two numbers are the generator's internal state. Get them from export_state or
from a saved copy of its result, not by computing them. Read them when you compare
osrlib with another implementation.
Examples:
from osrlib.core.rng import RngStream, RngStreams
stream = RngStreams(master_seed=42).get("combat")
stream.randbelow(20)
# Save the position, draw on, and a restored copy continues from the save.
snapshot = stream.export_state()
expected = stream.randbelow(20)
assert RngStream.restore(snapshot).randbelow(20) == expected
state
class-attribute
instance-attribute
The generator's 128-bit state, from 0 up to but not including 2**128. It changes with every draw.
RngStreams
RngStreams(master_seed: int)
All of a game's random number streams, forked from one master seed.
Make one with the seed you want the game to run on, then call
get for each stream you need. The container creates
a stream the first time you ask for its name and stores it, so if you ask again, you get
the same stream at the position you left it.
Keep one container for the whole game and pass streams out of it. Two containers with the same seed give the same numbers, so streams from a second container repeat the rolls the first one already made.
A GameSession has one of these, so you build
your own only when you run the kernel, osrlib's rules functions, without a session.
Save the position of every stream with
export_states and put them back with
restore_states. The names a session
uses are the members of StreamName, also listed in
the RNG streams reference.
Examples:
from osrlib.core.rng import RngStreams
streams = RngStreams(master_seed=42)
combat = streams.get("combat")
# The same name gives back the same stream, mid-sequence.
assert streams.get("combat") is combat
assert combat.randbelow(20) + 1 == 14
Create the container for a master seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
master_seed
|
int
|
The game's master seed, from 0 up to but not including 2**128. Any integer in range works. Record the one you used if you want to replay the game. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
master_seed
property
master_seed: int
Return the master seed every stream in this container is forked from.
Read it to record what a game was seeded with, so you can rebuild the same container later. You can't change it. To play on another seed, make a new container.
get
Return the stream with this name, and create it the first time you ask.
Pass the stream to the function that rolls, like roll.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The stream's name, like |
required |
Returns:
| Type | Description |
|---|---|
RngStream
|
The stream for that name, at whatever position it has reached. Asking twice gives the same stream, not a copy. |
Examples:
export_states
export_states() -> dict[str, RngStreamState]
Record the position of every stream in the container, keyed by name.
Write the result into your save file beside the master seed, and put it back with
restore_states when you load.
save_game does this for a session, so call it
yourself only when you save a game you built without one.
A name you've never passed to get is left out.
You haven't drawn from that stream, and get makes it from the master seed the
first time you ask for it.
Returns:
| Type | Description |
|---|---|
dict[str, RngStreamState]
|
One position per name you've passed to |
Examples:
restore_states
restore_states(states: dict[str, RngStreamState]) -> None
Put saved stream positions back, so each stream in a loaded game continues from where it stopped.
Call it on a container made with the master seed the game was saved under. The
container winds its streams back in place, so a stream you got from
get before this call is still the container's
stream, and you can keep drawing from it. Each stream named in states goes to its
saved position. Any other stream in the container goes back to the start of its
sequence, which is where a new container would start it. That includes a stream you
first asked for after the export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
states
|
dict[str, RngStreamState]
|
Positions from
|
required |
Examples:
from osrlib.core.rng import RngStreams
streams = RngStreams(master_seed=42)
combat = streams.get("combat")
combat.randbelow(20)
saved = streams.export_states()
expected = combat.randbelow(20)
# The stream you already have goes back to the saved position.
streams.restore_states(saved)
assert combat.randbelow(20) == expected
# A fresh container on the same seed picks up the next draw, not the first.
loaded = RngStreams(master_seed=42)
loaded.restore_states(saved)
assert loaded.get("combat").randbelow(20) == expected
StreamName
Bases: StrEnum
Every stream name a running session draws from.
Each member is a string, so RngStreams.get returns the same
stream for StreamName.COMBAT and "combat", and a save file uses the same key for both. Draw
with a member instead of a string you type out. A mistyped name raises no error:
get makes a new stream for it, and you get plausible
numbers from that stream instead of the one you meant.
Each *_STREAM constant in the library, like
COMBAT_STREAM, is one of these members, and each member's
docstring gives its constant. The member docstrings and
the RNG streams reference describe
what each stream covers.
A rule you write yourself isn't limited to these names.
RngStreams.get makes a stream for any string you pass it.
Examples:
from osrlib.core.rng import RngStreams, StreamName
streams = RngStreams(master_seed=42)
# A member is its own string, so the member and the written-out key are one stream.
assert StreamName.COMBAT == "combat"
assert streams.get(StreamName.COMBAT) is streams.get("combat")
CHARACTER_CREATION
class-attribute
instance-attribute
Creation draws: ability scores, the first-level hit die, and starting gold. Its constant is
CHARACTER_CREATION_STREAM.
ADVANCEMENT
class-attribute
instance-attribute
Hit dice rolled when a character gains or loses a level. Its constant is
ADVANCEMENT_STREAM.
COMBAT
class-attribute
instance-attribute
Battle resolution: attacks, damage, saves, morale, initiative, reactions. Its constant is
COMBAT_STREAM.
EFFECTS
class-attribute
instance-attribute
Draws inside the effects engine: onsets, rolled durations, revival countdowns. Its constant is
EFFECTS_STREAM.
MONSTER_SPAWN
class-attribute
instance-attribute
Hit points rolled as a monster instance is spawned from its template. Its constant is
MONSTER_SPAWN_STREAM.
NPC_PARTY
class-attribute
instance-attribute
NPC adventuring parties: composition, class and level, scores, hit points, spells. Its constant is
NPC_PARTY_STREAM.
MAGIC
class-attribute
instance-attribute
Spell resolution: targeting, damage, forced saves, dispel survival, turning undead. Its constant is
MAGIC_STREAM.
TREASURE
class-attribute
instance-attribute
Treasure generation, from the presence roll to each coin, gem, and magic item. Its constant is
TREASURE_STREAM.
WANDERING
class-attribute
instance-attribute
Wandering monsters: the check die, the table roll, group counts, variant picks. Its constant is
WANDERING_STREAM.
ENCOUNTER
class-attribute
instance-attribute
Encounter setup: surprise, distance, reaction, distraction, commanded group counts. Its constant is
ENCOUNTER_STREAM.
EXPLORATION
class-attribute
instance-attribute
Exploration: forcing doors, listening, searching, traps, tinder, thief skills. Its constant is
EXPLORATION_STREAM.
MONSTER_ACTION
class-attribute
instance-attribute
A monster action policy's draws: which action a group takes and at whom. Its constant is
MONSTER_ACTION_STREAM.
ADJUDICATION
class-attribute
instance-attribute
The referee's freeform dice rolls, separate from the streams rules functions draw from. Its constant is
ADJUDICATION_STREAM.
derive_init_pair
Compute the two numbers that start a named PCG64 stream.
You rarely call this. RngStreams.get calls it for
you, and RngStream.from_seed_material
wraps it in one step. Use it when you check how osrlib derives its streams against
another implementation, or when you build the same stream in another language.
The seed material is SHA-256(master_seed_bytes + b":" + stream_key_utf8), with the
master seed written as exactly 16 bytes, most significant first. The digest's first
16 bytes become the init state and its last 16 the sequence selector, each read most
significant byte first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
master_seed
|
int
|
The game's master seed, from 0 up to but not including 2**128. |
required |
key
|
str
|
The stream's name, like |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples: