osrlib.crawl.session
GameSession, the running game, which you drive one command at a time.
Build a session from a Party and an
Adventure with
GameSession.new, or restore one with
load_game. From there the loop is the same every
time: build a command from osrlib.crawl.commands, pass it
to GameSession.execute, and render the
CommandResult that comes back. A refused
command comes back with its reasons and changed nothing. An accepted one comes back
with the events it caused, which you turn into lines with
format_message or with a renderer of your own.
Draw each screen from GameSession.view
rather than from the session's attributes, because the player view leaves out what the
players mustn't see. Save the game with
save_game.
The rules functions in osrlib.core act on objects you pass them, and they
store nothing between calls. The session contains those objects for a whole game: the seeded
random streams, the id allocator, the active effects, the clock, the characters and live
monsters, the session flags (a key-value store for facts you track), the record
of fired triggers, the journal, the quest states, the listeners and their state, the
command and event logs, the session mode, and what play has changed on the map.
Because the session contains all of it, one save restores a game, and replaying the
command log from the same seed reaches the same game.
The other members of this module are records the session stores, which you read from a
view rather than build: JournalEntry,
QuestState and
ObjectiveState,
DeathRecord,
DefeatedMonsterRecord, and
DeprivationState. The *_STREAM constants
are the names of the random streams the crawl procedures draw from, and
LIGHT_EFFECT_KINDS and
DARKNESS_EFFECT_KINDS are the effect
kinds the session counts as light and darkness.
Which commands the session will accept depends on its
SessionMode: town between delves,
exploring on a dungeon grid, encounter when the party has met monsters and nobody
has attacked yet, and battle once a fight starts. In game_over and victory the
session has ended. The session refuses a command that doesn't belong to the current mode
with session.command.wrong_mode, and each command class lists the modes it's legal in.
To add behavior without changing osrlib, register a
Listener. A listener sees each accepted command's
events and reacts by executing ordinary commands, so the command log records everything it
does, and a replay repeats it like any other command. A listener can keep facts in the session flags by
executing SetFlag.
Typical usage:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.events import Visibility
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, MoveParty
from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.messages import format_message
from osrlib.persistence import load_game, save_game
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
corridor = 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=(corridor,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
# The session makes its own streams from this seed, separate from the creation stream above.
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
result = session.execute(MoveParty(direction=Direction.EAST))
print([format_message(event) for event in result.events if event.visibility is Visibility.PLAYER])
# ['The party moves to (1, 0), facing east.']
view = session.view(Visibility.PLAYER)
print(view.mode, view.location.position)
# exploring (1, 0)
restored = load_game(save_game(session))
print(restored.view(Visibility.PLAYER) == view)
# True
ADJUDICATION_STREAM
module-attribute
ADJUDICATION_STREAM = StreamName.ADJUDICATION
The name of the stream for the referee's dice rolls.
RollDice draws from it. It's separate from the streams the rules
use, so a roll for weather or a rumour never shifts a later attack or save.
DARKNESS_EFFECT_KINDS
module-attribute
DARKNESS_EFFECT_KINDS = frozenset({'darkness', 'continual_darkness'})
The effect kinds that put out the party's light while they last.
A darkness effect on any living member puts out all the party's light, because the spell's printed
radius covers a whole marching party. An effect whose params set blocks_infravision, like
continual darkness, stops infravision as well.
ENCOUNTER_STREAM
module-attribute
ENCOUNTER_STREAM = StreamName.ENCOUNTER
The name of the stream the encounter procedure draws from.
The engine draws from it for surprise, encounter distance, reaction rolls, and the distraction
check during a chase. It also draws from it when it rolls the size of a group for
SpawnMonsters and
SpawnNpcParty. See
WANDERING_STREAM for how stream names are used.
EXPLORATION_STREAM
module-attribute
EXPLORATION_STREAM = StreamName.EXPLORATION
The name of the stream the exploration procedures draw from.
The engine draws from it for forcing doors, listening, searching, springing traps, lighting a tinder
box, and thief skill checks. See WANDERING_STREAM for how
stream names are used.
LIGHT_EFFECT_KINDS
module-attribute
LIGHT_EFFECT_KINDS = frozenset({'light', 'continual_light'})
The effect kinds that give the party light: a lit torch or lantern, and the light spells.
GameSession.party_light checks each effect's kind
against this set. To make a light source of your own count as light, give its effect one of these
kinds.
MONSTER_ACTION_STREAM
module-attribute
MONSTER_ACTION_STREAM = StreamName.MONSTER_ACTION
The name of the stream a monster action policy draws from.
An ActionPolicy chooses what a monster group does in each
battle round, and at whom. Its stream is separate from the combat stream, so changing how monsters
choose their actions, or registering a policy of your own, never shifts the combat dice.
WANDERING_STREAM
module-attribute
WANDERING_STREAM = StreamName.WANDERING
The name of the stream the engine draws from for the wandering-monster check.
The engine draws from it for the check die, the encounter-table roll, the number of monsters, and the choice between variants of a table entry. Every draw in osrlib comes from a named stream, so adding a roll to one procedure can't shift the dice another procedure would have drawn.
You rarely need this name. It's the stream's key in a session's streams and in a save, so pass it
to RngStreams.get when you want to look the stream up, for
example to compare its state in a test. Don't draw from it during play. The engine's next wandering
rolls would change, and a replay of the command log would no longer reach the same game.
DeathRecord
Bases: BaseModel
When and how one party member died, recorded for the spells that bring the dead back.
The session writes one into
GameSession.death_records, keyed by
character id, as soon as a party member dies. The engine reads it when a character casts a
revival spell. Neutralize poison works only when poison was the cause, and only within a window
measured in rounds. Raise dead counts the days since the death.
The record is frozen. A member who dies again gets a new record, which replaces the old one.
round
instance-attribute
round: int
Where the clock stood at the death, in rounds since the session began. Both revival windows are measured from here.
cause
instance-attribute
cause: str
What killed the character: "poison", "damage", or "unknown". The session reads the
events of the command that killed the character, up to the death, and records the last cause
among them. A failed save versus death ray or poison, or a poison effect that ran its course,
gives "poison". Damage dealt gives "damage". With neither, the cause is "unknown". Only
neutralize poison treats "poison" differently from the other causes.
DefeatedMonsterRecord
Bases: BaseModel
One defeated creature, kept until the session awards its experience.
When an encounter ends, the session appends one for each defeated creature to
GameSession.defeated_monsters.
GameSession.award_adventure_xp
adds up their xp and clears the list when the party returns to town. Under a ruleset that
awards experience immediately, the session awards it and clears the list at the end of each
encounter instead.
Its fields contain the same facts as
MonsterDefeatedEvent.
DeprivationState
Bases: BaseModel
How long one member has gone without food and without water.
The session stores these in
GameSession.deprivation. Each time the clock
passes into a new game day, the session updates one for each living member, and creates it on that
member's first day. A day the member eats resets food_days to zero, and a day without food
adds one. Water works the same way for water_days. Whether the counts bring a
penalty depends on the ruleset option deprivation_penalties, described in
the adaptations register,
the page that lists where osrlib settles an ambiguous rule or supplies a default.
food_days
class-attribute
instance-attribute
food_days: int = 0
Consecutive days this member has gone without food.
water_days
class-attribute
instance-attribute
water_days: int = 0
Consecutive days this member has gone without water.
worst
property
worst: int
Return the worse of the two counts, which is the count the penalties depend on.
The two counts don't stack: going without both food and water is as bad as going without the worse of them, not twice as bad.
Returns:
| Type | Description |
|---|---|
int
|
The larger of |
GameSession
GameSession(*, party: Party, adventure: Adventure, ruleset: Ruleset, streams: RngStreams, master_seed: int)
A game in progress: the one object you execute commands against and read state from.
Make one with GameSession.new, or get
one back from load_game or
replay_game. Then run the loop: build a
command, pass it to execute, and render
the result. Draw each screen from view
rather than from the session's attributes, because a view contains only what its
audience may see. To add behavior of your own, register a
Listener with
register_listener.
save_game and load_game round-trip a session.
Every accepted command is on command_log and every event on event_log, and
replaying the command log from the same seed reaches the same game.
The attributes are public so that a referee screen and the save functions can read the whole state. Don't write to them. A change you make yourself isn't in the command log, so a replay won't match the session.
The same is true of the methods that change state, like
spawn,
advance_turns, and the experience
awards. The command handlers call them, and they aren't commands themselves, so the
command log doesn't record a call you make. If you call one during play, the game still
saves and loads, because load_game restores the
saved state, but replay_game won't reproduce
it. Where a command does the same job, execute the command instead.
Build a session from parts you already have.
You rarely call this yourself. Call GameSession.new
to start a game, or load_game to restore one, and both
call this constructor. It doesn't check the adventure's references, and it doesn't assign
character ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
party
|
Party
|
The party, in marching order, with ids already assigned. |
required |
adventure
|
Adventure
|
The adventure content. |
required |
ruleset
|
Ruleset
|
The ruleset in play. |
required |
streams
|
RngStreams
|
The seeded random streams. |
required |
master_seed
|
int
|
The seed those streams came from, kept so that |
required |
Raises:
| Type | Description |
|---|---|
ContentValidationError
|
If the adventure bundles monster, item, or spell ids that
collide with the built-in catalogs or with each other. This check still runs for
|
party
instance-attribute
The party, in marching order. The order determines who is in the front rank in a fight.
Outside a fight, ReorderParty sets the order. In a
battle, a member who withdraws alone trades places with the member named in
BattleDeclaration.replacement_id.
AddMember is the only command that adds a member. It adds
the member at the back.
adventure
instance-attribute
The adventure being played: its town, dungeons, quests, and any content it bundles. It's frozen, and a save contains a copy of it, so a saved game needs no other file to load.
ruleset
instance-attribute
The ruleset in play. Its options settle the rules that B/X leaves open, like when experience is awarded. See the adaptations register, the page that lists where osrlib settles an ambiguous rule or supplies a default.
streams
instance-attribute
The session's named random streams. Everything the engine rolls comes from one of them, and a save contains their positions, so a restored game continues the same way.
master_seed
instance-attribute
The seed the streams were built from. A save contains it and no view does, because knowing it would let a player predict every roll to come.
allocator
instance-attribute
allocator = IdAllocator()
The source of session ids. Every id the session hands out, for characters, monsters, NPC
adventurers, effects, encounter groups, and treasure, comes from here as <kind>-NNNN,
counting up for each kind. No id is random, so two runs of the same commands assign the
same ids.
ledger
instance-attribute
ledger = EffectsLedger()
The active effects: spells running, conditions, a torch burning down. Advancing the clock advances the ledger, which reports each effect that ticks or expires as an event.
clock
instance-attribute
clock = GameClock()
The game clock. clock.rounds is how much time has passed since the session began, in
rounds. Each turn the party spends exploring a dungeon counts toward its next required rest
and the next wandering-monster check, and each new day uses up food and water.
mode
instance-attribute
mode = SessionMode.TOWN
Which SessionMode the session is in, and so which
commands it will accept. A new session starts in town.
monsters
instance-attribute
monsters: dict[str, MonsterInstance] = {}
The live monsters, keyed by session id. Spawning adds to it, and a defeated monster is never removed, so a later event can still refer to it.
npcs
instance-attribute
The live NPC adventurers, keyed by session id. They are characters rather than monsters, and they fight under the same rules as the party.
flags
instance-attribute
The session flags: a key-value store that
SetFlag writes. The engine reads it to test the conditions
an adventure puts on triggers, quests, doors, and level exits. You choose the keys and
what they mean.
fired_triggers
instance-attribute
The ids of the triggers that have fired, in the order they first fired. Read it to find
out whether a trigger has fired before. Each firing, including a repeat, is in the event
log as a TriggerFiredEvent.
journal
instance-attribute
journal: list[JournalEntry] = []
The journal entries, in the order they were written. A player view contains the same list, and that's where you should read it from.
quests
instance-attribute
quests: dict[str, QuestState] = {
(quest.id): (
QuestState(
status="active" if quest.activation is None else "inactive",
objectives={
(objective.id): (ObjectiveState(revealed=not objective.hidden, complete=False))
for objective in (quest.objectives)
},
)
)
for quest in (adventure.quests)
}
The state of every quest in the adventure, keyed by quest id, in the order the adventure
lists them. See QuestState.
listener_state
instance-attribute
Each registered listener's state, keyed by its key. It's saved and restored with the
session, so a listener re-registered after a load picks up where it left off.
listeners
instance-attribute
The registered listeners, in the order they run. Listeners are code, so they aren't saved: register them again after a load.
command_log
instance-attribute
Every accepted command, in order. Refused commands are absent, because they changed
nothing. replay_game re-executes this list from the
master seed to rebuild the session.
event_log
instance-attribute
Everything that has happened, in order. Entries are events. A session restored from a save may also contain a raw mapping for an event this version of the library has no class for. The session keeps such a mapping rather than dropping it.
death_records
instance-attribute
death_records: dict[str, DeathRecord] = {}
When and how each dead party member died, keyed by character id. See
DeathRecord.
defeated_monsters
instance-attribute
defeated_monsters: list[DefeatedMonsterRecord] = []
The creatures defeated since the last award, which is what the experience award adds
up. See DefeatedMonsterRecord.
deprivation
instance-attribute
deprivation: dict[str, DeprivationState] = {}
Each member's food and water counts, keyed by character id. See
DeprivationState.
treasure_snapshot_cp
instance-attribute
treasure_snapshot_cp: int | None = None
What the party's treasure was worth, in copper pieces, when it left town, or None
when no delve is under way. The award pays for the difference between this and what comes
back.
odometer_thirds
instance-attribute
How far the party has walked during the current turn, in thirds of a foot. When it reaches three times the party's exploration rate, the clock advances one turn and this resets to zero.
turns_since_rest
instance-attribute
Turns since the party last rested. The engine counts these for the fatigue rule, and a rest resets them.
wandering_counter
instance-attribute
Turns since the last wandering check. When it reaches the level's interval, the engine makes the check and resets this.
noise_since_check
instance-attribute
Whether the party has made noise since the last wandering check. Every attempt to force a door makes noise, whether or not the door opens. Noise raises the next check's chance by 1 in 6, and the check clears it. A failed attempt also alerts the area beyond the door, so the party can't surprise the monsters there.
sleep_count
instance-attribute
How many nights or days the party has slept through. Preparing spells needs a sleep the caster hasn't already prepared from.
last_prepared_sleep
instance-attribute
The sleep_count at which each caster last prepared spells, keyed by character id. The
session uses it to enforce one preparation per sleep.
alerted_areas
instance-attribute
The keyed areas whose monsters have been alerted, as "{dungeon}:{level}:{area}"
references. Monsters that heard the party coming aren't surprised when it walks in.
heard_areas
instance-attribute
The keyed areas the party has heard something in, as "{dungeon}:{level}:{area}"
references. A party that knows what is behind the door isn't surprised by it.
encounter
instance-attribute
encounter: EncounterState | None = None
The encounter under way, as an EncounterState,
or None. It contains the monster groups, their distances, the monsters' reaction to the
party, and any chase in progress.
battle
instance-attribute
battle: BattleState | None = None
The battle under way, as a BattleState, or None.
It contains the round number and the rest of the battle's state from one round to the next.
action_policies
instance-attribute
Action policies for monster groups, keyed by encounter group id. To choose a group's
actions yourself, write an ActionPolicy and set
session.action_policies[group.id] to it, where group is an
EncounterGroup from session.encounter.groups.
Without an entry, a group uses the built-in policy for its kind. Policies are code, so they
aren't saved: register them again after a load.
dungeon_state
property
writable
dungeon_state: DungeonState
Everything play has changed on top of the adventure's map.
It holds where the party is, which cells it has walked and seen, door state, found and sprung traps, drop piles, and generated caches. The dungeons in the adventure never change.
When you set it, the session links the new state to this session's adventure. Then
DungeonState.door starts a door with no entry from
the door's DoorSpec.
metadata
property
Return the versions a client checks to confirm it's talking to a compatible engine.
Send it in a handshake, or show it on a debug screen. A save includes the same two values.
When you pass a save's engine_version to replay_game,
it refuses to replay the command log under a different engine version.
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
A dict 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.versioning import SCHEMA_VERSION
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
handshake = session.metadata
print(sorted(handshake), handshake["schema_version"] == SCHEMA_VERSION)
# ['engine_version', 'schema_version'] True
effective_monsters
property
effective_monsters: MonsterCatalog
Return the monster catalog this session resolves template ids against.
It's the built-in catalog plus whatever monsters the adventure bundles. Every part of the
engine that turns a template id into a creature reads it: spawning, keyed encounters,
wandering rows, listen checks. Use it when you want to look a template up the way the
session does, rather than calling load_monsters and missing
the monsters the adventure bundles.
Returns:
| Type | Description |
|---|---|
MonsterCatalog
|
The catalog. For an adventure that bundles nothing, it's the built-in catalog. |
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.data import load_monsters
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
# The adventure bundles a monster of its own, built from the goblin's entry.
cave_goblin = load_monsters().get("goblin").model_copy(update={"id": "cave_goblin", "name": "Cave Goblin"})
adventure = Adventure(
name="A First Delve",
town=TownSpec(name="Threshold"),
dungeons=(crypt,),
monsters=(cave_goblin,),
)
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
print(session.effective_monsters.get("cave_goblin").name, session.effective_monsters.get("goblin").name)
# Cave Goblin Goblin
effective_equipment
property
effective_equipment: EquipmentCatalog
Return the equipment catalog this session resolves item ids against.
It's the built-in catalog plus whatever items the adventure bundles, and every part of the
engine that turns an item id into an item reads it: treasure caches,
GrantItem, picking a drop pile back up. The town shop
is the exception: it sells from the built-in equipment lists, so a bundled item is never on
the shelf.
Returns:
| Type | Description |
|---|---|
EquipmentCatalog
|
The catalog. For an adventure that bundles nothing, it's the built-in catalog. |
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.commands import GrantItem
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
result = session.execute(GrantItem(character_id=hero.id, item_id="lantern", quantity=1))
acquired = result.events[0]
print([session.effective_equipment.get(item_id).name for item_id in acquired.item_ids])
# ['Lantern']
effective_spells
property
effective_spells: SpellCatalog
Return the spell catalog this session looks spell ids up in.
It's the built-in catalog plus whatever spells the adventure bundles. Every part of the
session that turns a spell id into a spell reads it: preparing, learning, and casting a
spell, a cast declaration in a battle, reading a scroll, an NPC adventurer's casting, the
temple, and a level drain, which forgets the memorized spells a lower level has no slot for.
Use it to show the name of a spell whose id is in a view, like an entry in
MemberView.spell_book, or to list the spells a
caster can choose with SpellCatalog.by_list.
load_spells doesn't have the spells the adventure bundles.
A character can have a spell in their spell book or memorized that this catalog doesn't
have, like a caster from a party made for another adventure. The session leaves the id on
the character. It refuses a PrepareSpells or a
CastSpell that names the spell, and a cast
declaration in a battle that names it, with the command's unknown_spell code. It refuses
a LearnSpell while the caster's book has the spell,
with magic.book.unknown_spell, because the room left in a book depends on the level of
each spell in it. A level drain, like a wight's touch, can't tell the level of a memorized
copy of the spell either, so the copy takes no slot. The drain doesn't forget it, and it
stays in its place in the character's memorized_spells.
Returns:
| Type | Description |
|---|---|
SpellCatalog
|
The catalog. For an adventure that bundles no spells, it's the built-in catalog. |
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.core.spells import SpellTemplate
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.data import load_spells
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
# The adventure bundles a spell made from the shield spell's entry.
shield = load_spells().get("shield")
glimmer = SpellTemplate.model_validate({**shield.model_dump(), "id": "glimmer", "name": "Glimmer"})
adventure = Adventure(
name="A First Delve",
town=TownSpec(name="Threshold"),
dungeons=(crypt,),
spells=(glimmer,),
)
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
print(session.effective_spells.get("glimmer").name, session.effective_spells.get("shield").name)
# Glimmer Shield
new
classmethod
new(party: Party, adventure: Adventure, *, seed: int, ruleset: Ruleset | None = None) -> GameSession
Start a new game: validate the adventure, assign character ids, and open in town.
Start every new game here. Build characters with
create_character, put them in a
Party in marching order, load or build an
Adventure, and call this. The session comes back in
town, at round 0, ready for the first
execute. To continue an existing game, use
load_game instead.
The session keeps the party you pass, not a copy, so from then on your character objects
are the session's live party members. To add a member once play has begun, execute
AddMember. It gives the new member the next
character-NNNN id from the session's IdAllocator.
Don't append to party.members yourself, because the command log wouldn't record the
change, and a replay wouldn't have the member.
This method checks the whole adventure before it builds anything, so an unknown monster id or a stair to a level that doesn't exist fails here, not partway through a delve.
The same seed and the same commands produce the same game, which is what makes a bug reproducible and a replay possible. Use a fresh seed for each game, and record it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
party
|
Party
|
The party, in marching order. Members that have no id get one here, as
|
required |
adventure
|
Adventure
|
The adventure content to play. |
required |
seed
|
int
|
The master seed every random draw in the session comes from. |
required |
ruleset
|
Ruleset | None
|
The ruleset options in play. Defaults to a stock
|
None
|
Returns:
| Type | Description |
|---|---|
GameSession
|
The session, in town, at round 0, with an empty command log. |
Raises:
| Type | Description |
|---|---|
ContentValidationError
|
If the adventure refers to something that doesn't exist, like an unknown monster or item id or a transition with no destination, or if it bundles a monster, item, or spell whose id is already a built-in id or another bundled entry's id. The message lists every problem found, and no member has been given an id. Fix the adventure and call again. The same adventure fails the same way every time. |
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
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
print(session.mode.value, session.clock.rounds, hero.id)
# town 0 character-0001
execute
execute(command: Command) -> CommandResult
Execute one command and return everything it caused.
This is the loop you run: build a command from
osrlib.crawl.commands, pass it here, check accepted, and
render either the rejections or the events. The command log records only what this method
executes, so if you change state only through it, you can always replay the game.
Validation runs first and changes nothing: a refused command draws no dice, spends no game
time, changes no state, and stays out of the command log. A rejection is the game refusing
the action, not an error. Show it to the player in your own words, from its code and
params. The
rejection codes reference
lists every code.
After an accepted command applies, the session records each party member's death with what
killed them. If the command's events killed or petrified a member and left no member
standing, which means neither dead nor turned to stone, the session ends in game_over,
and a GameOverEvent closes the result. A session
that has already ended stays in its mode.
The result contains the whole chain in log order: the handler's events, then, for each
registered listener in turn, the events of the commands that listener executed, however
deeply nested, followed by the events it returned itself. So one result is enough to
render the full reaction, and you don't have to read event_log to catch the rest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Command
|
The command to execute. |
required |
Returns:
| Type | Description |
|---|---|
CommandResult
|
The result. A refused command contains rejections and no events. An accepted one contains events and no rejections. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the command class has no handler, which means it was defined outside
osrlib rather than built from
|
RuntimeError
|
If a listener's |
Exception
|
Whatever a registered listener's |
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.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
result = session.execute(EnterDungeon(dungeon_id="crypt"))
print(result.accepted, [event.code for event in result.events])
# True ['exploration.location.entered']
again = session.execute(EnterDungeon(dungeon_id="crypt")) # already inside
print(again.accepted, again.rejections[0].code)
# False session.command.wrong_mode
register_listener
register_listener(listener: Listener) -> None
Register a listener, which then runs after every accepted command.
Listeners run in the order they were registered, after the command's handler. This is
how you add behavior without changing the engine. See
Listener for what one looks like and what it may do.
A listener is code, so a save doesn't include it, but a save does include its state.
Register your listeners again after load_game or
replay_game. After a load, each one gets its saved state
back under its key. A replay runs with no listeners registered, because the commands they
executed are already in the log.
Every call to the listener's handle gets the state dict the session has saved under its
key. A listener that executes commands is called again inside each of them, with the same
dict, so it updates that dict in place and returns it. If the outer call then returns any
dict other than the one the session has saved, an update would be lost, and
execute raises RuntimeError. A listener
that executes no commands may return a new dict, as the example below does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
listener
|
Listener
|
The listener to register. The session saves its state under its |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a listener with the same |
Examples:
from collections.abc import Sequence
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import TimeUnit
from osrlib.core.events import Event
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import AdvanceTime
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, save_game
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
class CommandCounter:
key = "command_counter"
def handle(self, events: Sequence[Event], state: dict) -> tuple[list[Event], dict]:
return [], {"commands": state.get("commands", 0) + 1}
session.register_listener(CommandCounter())
session.execute(AdvanceTime(n=1, unit=TimeUnit.TURN))
# A save keeps the listener's state but not the listener, so register it again after a load.
restored = load_game(save_game(session))
restored.register_listener(CommandCounter())
restored.execute(AdvanceTime(n=1, unit=TimeUnit.TURN))
print(restored.listener_state["command_counter"])
# {'commands': 2}
registry
Return every live entity in the session, keyed by id.
Party members come first in marching order, then monsters, then NPC adventurers. The engine passes this to the rules functions that look a target up by id. Use it when you resolve a rule yourself. For anything you draw on screen, read a view instead.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A fresh dict from entity id to the live object: |
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.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
session.spawn("goblin", 1)
for entity_id, entity in session.registry().items():
print(entity_id, entity.current_hp)
# character-0001 3
# monster-0001 1
combatant
combatant(combatant_id: str) -> MonsterInstance | Character | None
Return the monster or NPC adventurer with this id, or None.
An EncounterGroup contains ids that can be either,
and this resolves both without you having to know which. For a party member, call
member. For everything at once, call
registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
combatant_id
|
str
|
The entity id, as it appears on an encounter group or an event. |
required |
Returns:
| Type | Description |
|---|---|
MonsterInstance | Character | None
|
The live |
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.commands import EnterDungeon, SpawnMonsters
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
session.execute(SpawnMonsters(template_id="goblin", count_fixed=2, distance_feet=30))
for group in session.encounter.groups:
for monster_id in group.monster_ids:
monster = session.combatant(monster_id)
print(monster_id, monster.template.name, monster.current_hp)
# monster-0001 Goblin 1
# monster-0002 Goblin 3
member
Return the party member with this id.
The ids are the ones events use, so this is how you get from an event to the character
it's about. It is Party.member with the session's
party filled in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character_id
|
str
|
The member's session id, like |
required |
Returns:
| Type | Description |
|---|---|
Character
|
The member, living or dead. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no member of the party has that id. |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.items import Coins
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import GrantCoins
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
result = session.execute(GrantCoins(character_id=hero.id, coins=Coins(gp=25)))
recipient = session.member(result.events[0].character_id)
print(recipient.name, recipient.inventory.purse.gp)
# Hild 125
spawn
spawn(template_id: str, count: int, *, alignment: Alignment | None = None) -> list[MonsterInstance]
Spawn monsters into the session and return them.
Each instance gets hit points rolled from the seeded spawn stream and an id from the session
allocator, and is added to monsters, where the rest of the engine can find it.
Spawning alone puts nothing in front of the party, and the session mode doesn't change.
To field the monsters, pass them to
start_encounter. A monster that regenerates,
like a troll, starts to regenerate when its encounter opens, not when it spawns.
To put monsters in front of the party as the referee, execute
SpawnMonsters instead. In one command, it spawns
them and opens an encounter with them, or adds them to the open one. This method isn't a
command, so the command log doesn't record it, and
replay_game won't reproduce a game if you call it
during play.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_id
|
str
|
Any id in the session's
|
required |
count
|
int
|
How many to spawn. |
required |
alignment
|
Alignment | None
|
An alignment to give them instead of the template's, for keyed content whose author wants, say, lawful goblins. |
None
|
Returns:
| Type | Description |
|---|---|
list[MonsterInstance]
|
The new instances, in spawn order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the catalog has no such template id, or if |
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.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
goblins = session.spawn("goblin", 2)
print([(goblin.id, goblin.current_hp) for goblin in goblins])
# [('monster-0001', 1), ('monster-0002', 3)]
# Spawning opens no encounter: the session is still exploring.
print(session.combatant("monster-0002").template.name, session.mode.value)
# Goblin exploring
advance_rounds
Advance the clock by rounds and return what happened while it moved.
The commands advance time themselves, so you call this only when you are resolving
something outside the command set. To move the clock as the referee, execute
AdvanceTime instead. For rounds, its handler calls
this method, and the command log records the command.
As time passes, effects tick and expire, a light burning out leaves the party in the dark,
and each new day uses up food and water. The ledger reports an expiring effect as an event
only the referee sees, so for an expiring light the session adds a
LightEvent, which the players see and whose source is
the light that went out.
To advance whole turns, with the required rests and the wandering-monster checks, call
advance_turns instead. This method runs
neither.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
How many rounds to advance. |
required |
Returns:
| Type | Description |
|---|---|
list[Event]
|
The ledger's events, each expired light's event followed by its |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
advance_turns
advance_turns(
turns: int, *, resting: bool = False, hidden: bool = False, field: bool | None = None
) -> tuple[list[Event], bool]
Advance whole turns, one at a time, applying the rules that run each turn.
This is the time path the exploration commands use, and the one to call when you are resolving elapsed time yourself. If the clock is partway through a turn, this method first advances it to the next turn boundary, so an action that costs a turn includes the part of the turn the party had already spent walking.
For each turn, the clock and the active effects advance, and a new day uses up food and water.
The field argument says whether the dungeon rules for rest and wandering monsters
apply. By default they apply while the session is in exploring mode, that is, while
the party explores a dungeon. When they apply:
- Each turn counts toward the party's next required rest, unless the party is resting.
- Each turn counts toward the next wandering-monster check, which runs when it's due.
- A check that produces an encounter stops the advance at that turn, because the party now has something else to deal with. The second return value is then True.
- The advance stops as soon as no party member is alive, because these rules apply only while someone is.
When they don't apply, as in town or on the road, the advance keeps going even with every member dead. The time limit on bringing a dead character back has to keep running while the party lies dead.
To move the clock during play, execute
AdvanceTime or Rest
instead, which the command log records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
turns
|
int
|
How many turns to advance. |
required |
resting
|
bool
|
True while the party is resting. Resting turns don't count toward the next required rest. Resting alone doesn't change the wandering chance. |
False
|
hidden
|
bool
|
True while the party hides, resting quietly in an out-of-the-way place. It
lowers the chance of each wandering check in the span by 1 in 6. A
|
False
|
field
|
bool | None
|
Whether the dungeon rules for rest and wandering monsters apply. Defaults to
whether the session is in |
None
|
Returns:
| Type | Description |
|---|---|
tuple[list[Event], bool]
|
The events, and True when a wandering encounter interrupted the span before it ran out. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
# Three turns in the dungeon: this level's wandering check runs after the second.
events, interrupted = session.advance_turns(3)
print([event.code for event in events], interrupted, session.clock.rounds)
# ['exploration.wandering.checked'] False 180
party_light
Return whether the party has light, and whether infravision works.
Most of exploration needs light. Call this to decide whether to dim the screen or disable a search button. The engine calls it before it lets the party read, search, or see an encounter coming.
The party has light when any living member has an active effect whose kind is in
LIGHT_EFFECT_KINDS. An effect whose kind is in
DARKNESS_EFFECT_KINDS, on any living member,
puts that light out while it lasts, because the spell's printed radius covers a whole
marching party. Some darkness stops infravision as well.
Returns:
| Type | Description |
|---|---|
tuple[bool, bool]
|
A pair: whether the party is lit, and whether infravision works. Infravision is
allowed unless a darkness effect blocks it. Whether a member has infravision at all
is |
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.commands import EnterDungeon
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
# Nobody has lit a torch yet, so the party stands in the dark.
lit, infravision_works = session.party_light()
print(lit, infravision_works, session.member_has_infravision(hero))
# False True False
bright_light
bright_light() -> bool
Return whether the party has light as bright as daylight.
The wandering-monster chance goes up by 1 in 6 for a party that can be seen coming. osrlib treats the flame of a torch or lantern as the baseline for the printed chance, so only a light whose data gives its brightness as daylight counts here, which in the built-in catalog means continual light. See the adaptations register, the page that lists where osrlib settles an ambiguous rule or supplies a default.
Returns:
| Type | Description |
|---|---|
bool
|
True when a living member has a light effect whose brightness is daylight. |
member_has_infravision
Return whether one member can see in the dark.
Either the class has it, as the dwarf and the elf do, or an effect has granted it. The engine calls this when it decides whether a character can act in the dark, and when it sets the party's chance of being surprised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
member
|
Character
|
The member to test. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when that member has infravision. |
party_valuation_cp
party_valuation_cp() -> int
Return what the party's treasure is worth right now, in copper pieces.
The value is in copper so that no rounding is lost along the way. The award converts it to gold once, at the end. The session measures the value when the party leaves town and again when it comes back, and the difference is the treasure experience.
Every member counts, the dead included, because treasure carried out on a body still came home. Magic items and mundane gear count for nothing: magical treasure grants no experience, and selling off used gear is below the level of detail osrlib simulates.
Returns:
| Type | Description |
|---|---|
int
|
The coins, in copper, plus every valuable's listed value, converted to copper. |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.items import Coins
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import GrantCoins
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
before = session.party_valuation_cp()
session.execute(GrantCoins(character_id=hero.id, coins=Coins(gp=25, sp=5)))
print(session.party_valuation_cp() - before)
# 2550
snapshot_treasure
Record what the party's treasure is worth as it leaves town, for the return award.
The session stores the value in
treasure_snapshot_cp.
The EnterDungeon handler calls this method, so you
don't have to. Call it yourself only when you start a delve some other way.
award_adventure_xp
Pay the end-of-adventure experience award and return its events.
TravelToTown calls it under the default ruleset,
where experience is awarded for making it back alive, so you don't call it yourself.
The award is what the defeated creatures were worth, plus one experience point for each gold piece of treasure the party gained since it left town. A loss of treasure counts as zero. The total divides evenly among the survivors, rounded down, and each survivor gets one share. The dead count toward the treasure that came home and take no share, and a party that lost everyone is awarded nothing.
Whatever happens, the method clears
defeated_monsters and resets
treasure_snapshot_cp, so the next
delve starts from zero.
Returns:
| Type | Description |
|---|---|
list[Event]
|
The |
award_immediate_xp
Divide one pool of experience among the survivors now, and return its events.
Under a ruleset that awards experience immediately, the session calls this at the end of
each encounter and each time the party takes treasure, so you don't call it. It
divides the pool the way the return award does: evenly among the living, rounded down, with
the remainder dropped. To award one character an amount, execute
AwardXP instead, which the command log records and a replay
repeats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
int
|
The pool to divide. |
required |
Returns:
| Type | Description |
|---|---|
list[Event]
|
Each survivor's award event and, where one gained a level, the level event. An empty list when nobody is alive or the share rounds to zero. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
view
view(visibility: Visibility) -> PlayerView | RefereeView
Return a snapshot of the session for one audience: the players or the referee.
Draw from a view rather than from the session's attributes. The player view has a fixed
list of fields, each one something a player may be shown, so a screen built on it can't
reveal the map the party hasn't explored, the monsters' hit points, or the referee's rolls.
The referee view contains the rest, for a referee screen, an LLM running the game, or a
test. It has one typed field for each group of data the save contains, so you read
view.monsters[0].current_hp and view.flags["key"] with the models this reference documents.
In a networked game, keep the session and the referee view on the server, and send the client the player view or the player-visibility events. Neither view contains the master seed. Only the save contains it.
Views are frozen and built fresh from the current state each time, never from the event log, so call this again after each command rather than keeping one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
visibility
|
Visibility
|
|
required |
Returns:
| Type | Description |
|---|---|
PlayerView | RefereeView
|
A |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.events import Visibility
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
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
level = LevelSpec(number=1, width=1, height=1, entrance=(0, 0))
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
player = session.view(Visibility.PLAYER)
referee = session.view(Visibility.REFEREE)
print(player.mode, player.party[0].name)
# exploring Hild
# The referee sees the session flags; the player whitelist has no such field.
print(referee.flags, "flags" in player.model_dump())
# {} False
# Neither view carries the master seed.
print("master_seed" in referee.model_dump())
# False
JournalEntry
Bases: BaseModel
One entry in the party's journal: a line of the adventure's story, with the time it was written.
AddJournalEntry writes entries. So do the quest
commands, like ActivateQuest, which add the
adventure's text for each step of a quest. Read the journal from
PlayerView.journal, a tuple of these in the order
they were written.
Entries are appended and never changed. Each one records the clock at the moment it's written, so you can show when it happened from the view alone, and a save made without its event log still has the time of every entry.
text
class-attribute
instance-attribute
The entry's text, from your code or from the adventure document. osrlib never writes it, and it's never empty.
Listener
Bases: Protocol
An object you register on a session to react to what happens in play.
A listener adds behavior to a game without changing osrlib, like a trap that teleports the
party, a cursed item that speaks, or a score. Write a class with a key attribute and a
handle method, and register an instance with
GameSession.register_listener.
After every accepted command, the session calls each listener's handle in the order they
were registered. It passes the command's events and the listener's saved state. To play the
triggers and quests an adventure defines, register
Interpreter, a listener osrlib provides.
A listener doesn't change game state directly. It reacts by executing ordinary commands on the session. handle
doesn't receive the session, so pass the session to your listener when you construct it, as
Interpreter takes it. The command log records those commands, so a replay
from the seed produces the same game. The session logs the events of those commands too, so handle doesn't return
them. Returning them would put them in the log twice. The list handle returns is for events the listener builds
itself, which the session would not otherwise log.
A listener sees the events of every accepted command once, including the commands that other listeners execute, because the session calls the listeners for each of those too. It sees an event another listener returned only when that listener was registered before it.
The session saves each listener's state under its key, and every call to handle gets the
dict saved there, so a listener needs no separate storage. A listener is code and isn't saved,
so register it again after load_game.
A listener that executes a command is called again, for that command's events, before the
first call returns. Both calls get the same dict. Update it in place and return it, and the session
saves every update. If the inner call returns a new dict instead, the session saves that one.
Once the listener has been called again, the outer call has to return the dict the session has
saved under its key. Any other dict, like a copy the outer call made before it executed the
command, would overwrite what the inner call saved, so the session raises RuntimeError instead.
A listener that isn't called again inside its own call, because it executed no command that the
session accepted, may return a new dict, as the example below does.
Examples:
from collections.abc import Sequence
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.events import Event
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, MoveParty
from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
rules = Ruleset()
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
name="Hild",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=rules,
stream=stream,
).character
corridor = 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=(corridor,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
class StepCounter:
key = "step_counter"
def handle(self, events: Sequence[Event], state: dict) -> tuple[list[Event], dict]:
steps = state.get("steps", 0)
steps += sum(1 for event in events if event.code == "exploration.party.moved")
return [], {"steps": steps}
session = GameSession.new(Party(members=[hero]), adventure, seed=7)
session.register_listener(StepCounter())
session.execute(EnterDungeon(dungeon_id="crypt"))
session.execute(MoveParty(direction=Direction.EAST))
print(session.listener_state["step_counter"])
# {'steps': 1}
key
instance-attribute
key: str
The listener's name, unique within the session. Its state is saved and restored under this
key, so keep it stable across releases of your game.
register_listener refuses a second
listener with a key that's already registered.
handle
React to one command's events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
Sequence[Event]
|
The command's events, in the order they happened, followed by the events that listeners registered before this one returned. |
required |
state
|
dict
|
The dict the session has saved under this listener's key: the state this listener returned last time, or the state a save restored. It's an empty dict on the first call. A call made inside a command this listener executed gets the same dict as the call that executed it. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[Event], dict]
|
The events this listener built itself, which the session appends to the command's
result and to the event log, and the state for the session to save. Return an empty list when the
listener reacted by executing commands, because their events are already logged. A
listener that executes commands returns the |
ObjectiveState
Bases: BaseModel
One objective's state in play: whether the party may see it, and whether it's done.
The session creates one for each objective in the adventure and stores them in
QuestState.objectives. A player view includes
the revealed objectives of active quests, and the referee view includes them all.
Both flags change only from false to true, because no quest command turns either one off. Completing an objective reveals it too, so the players see an objective they finished before anyone told them about it.
revealed
instance-attribute
revealed: bool
Whether the party may be shown this objective. It starts true unless the objective's
ObjectiveSpec.hidden is true, and
RevealObjective turns it on.
complete
instance-attribute
complete: bool
Whether the objective is done. CompleteObjective
turns it on, and turns revealed on with it.
QuestState
Bases: BaseModel
One quest's state in play: where it stands, and where each of its objectives stands.
The session creates one for each quest in the adventure and stores them in
GameSession.quests, keyed by quest id. Only the
quest commands change them: ActivateQuest,
RevealObjective,
CompleteObjective, and
CompleteQuest. So a replay of the command log
rebuilds them exactly.
A quest with no activation clause, meaning its
QuestSpec.activation is None, starts active,
because the party has it from the start. The rest start inactive and wait for
ActivateQuest.
status
instance-attribute
status: Literal['inactive', 'active', 'completed']
Where the quest stands. It moves from inactive to active to completed and never
goes back.
objectives
instance-attribute
objectives: dict[str, ObjectiveState]
The state of each objective, keyed by objective id, in the order the adventure lists them
in QuestSpec.objectives.