osrlib.persistence
Save a game, load it back, or rebuild it by replaying what the player did.
A stored game becomes a running GameSession again in
one of two ways: load or replay. Save with save_game, then restore with one of the other two:
save_game: a session in, a save document out.load_game: a save document in, a session ready to continue out. Use this to resume play.replay_game: the seed, the starting party, the adventure, the ruleset, and the command log in, the same session rebuilt out. Use this to check that the commands reproduce the game.
These members are for special cases:
session_state: a session in, the save's contents without the version stamps out.MIGRATIONS: the stepsload_gameruns to upgrade an older save.
Most of the time you save and load. save_game turns a
session into a plain dictionary you can write as JSON.
load_game turns that dictionary back into a session that
continues from where it was. A save includes the adventure content, so you don't need any
other file to load it, and you can give a player a save without the adventure file it came from.
The other way is replay. replay_game starts from the
master seed, the party as it was before play began, the adventure, the ruleset, and the list
of commands the session accepted. It runs the whole game again from the first command.
Every random draw in osrlib comes from a seeded stream, so the second run makes the same
rolls as the first. The replayed session matches a load of the same game, except for what
listeners added: the events they wrote themselves and their saved state. The match also
requires that you made the party document before any session used the party, because
GameSession.new assigns the member ids itself. Use
replay to audit a game, to reproduce a bug report, or to check that a rules change changed
nothing it shouldn't have.
A save contains the session's state: the party, the adventure content, the ruleset, the
explored dungeon, the clock, the id allocator, the active effects, the spawned monsters and
NPCs, flags, fired triggers, the journal, quest progress, listener state, death records,
defeated monsters, the session mode, the exploration counters, any encounter or battle in
progress, every RNG stream's position, and the master seed. Beside that state, the save
contains two logs of what happened: the accepted commands, and the events, unless you leave
the events out. load_game rebuilds the session from the state and doesn't re-run any of the
logged commands.
The two logs have different uses. replay_game runs the
command log, which every save includes. The event log is the transcript you show the player.
Leave it out with include_event_log=False when the save is only for resuming play.
A save is a stamped document of kind "save", the envelope that
osrlib.versioning describes. The envelope has two version stamps.
schema_version is the save format. load_game runs an
older payload through MIGRATIONS, one step at a time,
until it reaches the format this osrlib reads. engine_version is the osrlib version that
wrote the save, and replay_game checks it, because the same commands under different rules
can produce a different game. replay_game raises
ReplayVersionError when you pass it the recorded
version and it doesn't match. Loading works across engine versions, because load_game reads
the saved state instead of re-running the commands. You can't load a save with a newer
schema_version than this osrlib reads.
Typical usage:
import json
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character, party_to_document
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.persistence import load_game, replay_game, save_game, session_state
rules = Ruleset()
roll = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
pc = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=roll)
# Keep the party as it is before any session uses it. A replay starts from this document.
starting_party = party_to_document([pc.character])
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[pc.character]), adventure, seed=7, ruleset=rules)
session.execute(EnterDungeon(dungeon_id="crypt"))
# Save, write it out, read it back, and continue from where the party stood.
document = save_game(session)
restored = load_game(json.loads(json.dumps(document)))
print(restored.mode.value)
# exploring
# Replay reaches the same session from the seed and the commands alone.
replayed = replay_game(7, starting_party, adventure, rules, session.command_log)
print(session_state(replayed) == session_state(session))
# True
MIGRATIONS
module-attribute
MIGRATIONS: Mapping[int, Callable[[dict], dict]] = MappingProxyType(
{1: migrate_1_to_2, 2: migrate_2_to_3, 3: migrate_3_to_4}
)
The steps that upgrade an old save payload, one schema version at a time.
Each key is a schema version n, and its value is a function that takes a payload written
at version n and returns a new payload in the format of version n + 1. A step doesn't
change the payload you pass it. Each step is a function of this module too, like
migrate_3_to_4, and its entry says what the step changes.
load_game runs the steps for you, from the version the
document was stamped with up to SCHEMA_VERSION, so a
save from an older release loads without any code from you.
Read it to see which versions a save can be upgraded from. It has a step for every schema
version from 1 up to the one before SCHEMA_VERSION. The mapping is read-only, so assigning
or deleting an entry raises TypeError.
load_game
load_game(document: Mapping[str, object]) -> GameSession
Restore a session from a save document.
Pass it the save document, parsed back from JSON, and you get a
GameSession in the state it had when
save_game wrote it. The party is in the same place, with
the same clock, hit points, and RNG streams, so the next roll is the roll the saved game
was about to make.
Code you attached to the session doesn't come back, because a save can't contain code. The
restored session has no listeners and no
action_policies. Before you execute
another command, call register_listener
again for each listener, including the Interpreter
if you use it, and set your action policies again. Each listener's state is in the save,
under its key, and the restored session passes it to the listener on its next call.
You don't need to do anything for an older save. The call checks the document, then
upgrades a copy of the payload through MIGRATIONS, one
schema version at a time, before it rebuilds anything. The call doesn't change document,
and the restored session shares nothing with it.
A newer osrlib can add event types and message codes within the same schema version. The call keeps an event as a dict when this osrlib doesn't define its type, or defines the type but not its code. The next save writes the dict back out unchanged, so the log loses no entries when an older osrlib loads it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Mapping[str, object]
|
A document that |
required |
Returns:
| Type | Description |
|---|---|
GameSession
|
The restored session, with no listeners or action policies registered. |
Raises:
| Type | Description |
|---|---|
ContentValidationError
|
If the document isn't a save, if the envelope or the payload is malformed, if its schema version is below 1, or if a logged command is of a type this osrlib doesn't define. A retry with the same document fails the same way. |
SaveVersionError
|
If the document's schema version is newer than this osrlib reads. Tell the player to upgrade osrlib. The file itself is fine. |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.dungeon import DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.persistence import load_game, save_game
rules = Ruleset()
roll = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
pc = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=roll)
party = Party(members=[pc.character])
level = LevelSpec(number=1, width=2, height=1, entrance=(0, 0), edges={"1,0:west": Edge(kind=EdgeKind.OPEN)})
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(party, adventure, seed=7)
document = save_game(session)
restored = load_game(document)
assert save_game(restored) == document
migrate_1_to_2
Migrate a schema 1 payload to schema 2 by dropping the recovered-treasure ledger.
The session works out the end-of-adventure award from the valuation it records when the party leaves town, so a version-1 save drops the ledger field. A version-1 save has no NPC adventurers, which arrived with version 2, so the NPC list starts empty.
load_game runs this step for you through
MIGRATIONS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict
|
The |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new payload in the schema 2 format. |
migrate_2_to_3
Migrate a schema 2 payload to schema 3 by rewriting a treasure trap's trigger to "open".
In schema 3, TrapSpec rejects trigger="enter" on
kind="treasure". The cache code never read that value, so rewriting it to
"open", the one action that springs a cache, loses nothing. The embedded adventure is
the only part of a save with trap specs in it, and a treasure trap sits on a feature,
either on an area or on a level.
load_game runs this step for you through
MIGRATIONS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict
|
The |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new payload in the schema 3 format. |
migrate_3_to_4
Migrate a schema 3 payload to schema 4 by clearing a logged withdraw off every declaration.
Schema 4 drops "withdraw" from
BattleDeclaration.move, leaving the two
defensive moves the OSE SRD prints, so a declaration that still has the value no longer
parses. Schema 3 accepted it on any declaration, since no validator checked move against
action, and the migration clears it wherever it sits. A move declaration becomes
action="hold" with no move, which is how that round played: the round resolver had no
branch for a withdraw, so the member who declared one stood there. On any other action osrlib
never read the move field, so the migration clears it and leaves the action as it is. The command log is the
only place a declaration is stored, since a battle's state contains its round bookkeeping and not
the round's declarations.
Schema 4 also drops two fields that osrlib never wrote: the boolean on
EncounterGroup that marked a monster group as having
given itself up, and discovered_features on the dungeon state. It also drops a character's
computed literacy property, which was never a field and never reached a payload.
This migration doesn't clear either field. The models that read those payloads ignore a key they
don't declare, so a schema 3 save with either one loads with the value dropped and nothing else
changed. The message code for that outcome, battle.side followed by the name of the removed
EncounterGroup field, is gone too.
MonsterFledEvent no longer accepts the code, so an
event with it fails to parse. No log contains one, because osrlib never set the field.
load_game runs this step for you through
MIGRATIONS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict
|
The |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new payload in the schema 4 format. |
replay_game
replay_game(
seed: int,
party_document: Mapping[str, object],
adventure: Adventure,
ruleset: Ruleset,
commands: Sequence[Command | Mapping[str, object]],
*,
recorded_engine_version: str | None = None
) -> GameSession
Rebuild a session by running its recorded commands again from the seed.
load_game restores a stored state. This call plays the
game a second time instead: it starts a new session on the same master seed, then
executes every command in the log, in order. Each random draw comes from a seeded stream,
so the rolls come out the same, and the session you get back matches a load of the same
save, apart from the state and the events that listeners returned.
Use it to audit a game, to reproduce a player's bug report from their save, or to check
that a rules change you made changed nothing it shouldn't have. Use load_game for
everything else, including resuming play. A replay re-runs the whole game, and gives you
nothing a load doesn't.
To replay a stored game, load its save with load_game first. Take the seed, the
adventure, the ruleset, and the command log from the restored session's master_seed,
adventure, ruleset, and command_log. load_game upgrades an older save to the
current schema, so those values are in the format this osrlib reads. Take
recorded_engine_version from the save document's engine_version.
The save doesn't contain the starting party, so keep it yourself. party_document must be
the party as it was before any session used it, because
GameSession.new assigns member ids itself, in
party order, the same way both times. Make that document with
party_to_document when you create the party,
and keep it beside your saves.
A replay runs with no listeners registered. The original session accepted and logged each
command a listener executed, like an Interpreter
running a trigger's consequences, so the replay executes it again from the log. A listener
registered on a replay would execute those commands a second time, and the replay would no
longer match the original game.
That's a limit of replay: the replayed session has no listener state and none of the
events a listener returned. Its listener_state is empty, and its event_log lacks those
events. If your game needs that state, load the save with load_game, which restores
listener_state and the event log. If a replay has to rebuild something a listener
tracks, have the listener record it with a command, like
SetFlag, so the command log contains it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The master seed the original session ran under, from the save's |
required |
party_document
|
Mapping[str, object]
|
The starting party, from
|
required |
adventure
|
Adventure
|
The adventure the game was played in. |
required |
ruleset
|
Ruleset
|
The ruleset the game was played under. A different one can change outcomes, and this call doesn't detect that. |
required |
commands
|
Sequence[Command | Mapping[str, object]]
|
The accepted commands, in order, either as
|
required |
recorded_engine_version
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
GameSession
|
The replayed session, in the state the original reached, with no listeners registered. |
Raises:
| Type | Description |
|---|---|
ReplayVersionError
|
If |
ContentValidationError
|
If |
SaveVersionError
|
If a newer osrlib wrote |
Examples:
import json
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character, party_to_document
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.persistence import load_game, replay_game, save_game, session_state
rules = Ruleset()
roll = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
pc = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=roll)
# Keep the party document from before play: the save doesn't contain it.
starting_party = party_to_document([pc.character])
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[pc.character]), adventure, seed=7, ruleset=rules)
session.execute(EnterDungeon(dungeon_id="crypt"))
stored = json.dumps(save_game(session))
# Later: read the save back, load it, and replay its command log from the seed.
document = json.loads(stored)
saved = load_game(document)
replayed = replay_game(
saved.master_seed,
starting_party,
saved.adventure,
saved.ruleset,
saved.command_log,
recorded_engine_version=document["engine_version"],
)
print(session_state(replayed) == session_state(saved))
# True
save_game
save_game(session: GameSession, *, include_event_log: bool = True) -> dict
Serialize a session to a save document you can store.
To write a game to disk, pass the result to json.dumps and store the string wherever
you keep saves. Restore it later with load_game. Call
this as often as you like. It reads the session and changes nothing, so you can save in
any mode, including during an encounter or a battle.
The result is a stamped document of kind "save", the envelope that
osrlib.versioning describes. The session state is under payload,
beside the schema and engine versions. load_game checks the schema version before it
reads the payload. session_state gives you the
payload without the envelope, for when you embed it in a document of your own instead
of storing it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
GameSession
|
The session to save. |
required |
include_event_log
|
bool
|
Whether to include the event log. Pass False to include only the
state and the command log, which is all |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
A new dict of JSON-compatible values with |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.persistence import save_game
rules = Ruleset()
roll = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
pc = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=roll)
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[pc.character]), adventure, seed=7, ruleset=rules)
document = save_game(session)
print(document["kind"], sorted(document))
# save ['engine_version', 'kind', 'payload', 'schema_version']
session_state
session_state(session: GameSession, *, include_event_log: bool = True) -> dict
Serialize a session's whole state, without the document envelope around it.
This is the payload that save_game wraps in its
envelope. Use it when you don't want the envelope: to embed a session in a larger document
of your own, to compare two sessions field by field, or to inspect what a session contains.
Call save_game instead whenever you store the result. A payload with no envelope has no
version stamps, so load_game can't read it, and nobody
can tell later which osrlib wrote it.
The call doesn't change the session, and the result shares nothing with it. You can keep the result, edit it, and serialize it whenever you like, and the session stays as it was.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
GameSession
|
The session to serialize, in any mode, including during an encounter or a battle. |
required |
include_event_log
|
bool
|
Whether to include the event log. Pass False to leave it out, which makes a long game's payload much smaller. The command log is included either way, because a replay needs it. |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
A new dict of JSON-compatible values, ready for |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.persistence import session_state
rules = Ruleset()
roll = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
pc = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=roll)
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[pc.character]), adventure, seed=7, ruleset=rules)
state = session_state(session, include_event_log=False)
print(state["master_seed"], state["mode"], "event_log" in state)
# 7 town False