Skip to content

osrlib.crawl.views

The two views of a session: the fields a player may see, and the referee's full state.

A view is the snapshot you render: everything on the screen after a command, in one frozen object.

Call GameSession.view with a Visibility after each command. Visibility.PLAYER returns a PlayerView, what a player may see, and Visibility.REFEREE returns a RefereeView, the full state. build_player_view and build_referee_view are the builders that method calls. The other classes here are the parts of a player view, and ExplorationCounters is a part of the referee view.

Events report what just happened, and a view shows what is true now. A view is built from the session's current state, never by reading the event log, though the referee view includes the log as one of its fields. The ids a view includes, MemberView.id and EncounterGroupView.id, are the ids the commands in osrlib.crawl.commands take.

The player view has a fixed list of fields, each one safe to show a player. It includes:

  • each party member's character sheet, with every number on a B/X character sheet, and the party's location and facing
  • the mapped cells and their edges: the cells the party walked, the cells its light has shown it, and what its light shows right now, with an undiscovered secret door shown as wall
  • the dropped piles on cells the party has walked, and the caches it has emptied
  • the active effects on party members, with their remaining durations
  • the elapsed clock and the session mode
  • the journal, and the active quests with their revealed objectives
  • the public state of the current encounter or battle
  • fatigue, exhaustion, and deprivation status
  • the adventure's and the town's public prose

It never includes:

  • geometry the party hasn't explored, or undiscovered traps and secret doors
  • monster hit points or stat internals
  • the outcomes of referee-visibility rolls
  • session flags, trigger fired-marks, or referee notes
  • the logic of a quest (its activation clauses, patterns, conditions, and rewards), its hidden objectives, or any quest that isn't active, whether not yet taken on or already finished
  • the RNG state or the master seed, which only the save contains

The referee view includes everything else the save does, except the random streams' positions and the master seed. Use it for an LLM referee, a debugging panel, or a test. Its fields are the groups session_state writes, so view.monsters[0].current_hp and view.flags["key"] have the types this reference documents, and view.model_dump(mode="json") is that save data without those two keys. Don't send it to a player's client. In a networked game, keep the session and the referee view on the server, and send only the player view, or the player-visibility events. The guide Views and visibility shows both views in a running front end.

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, 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))

# The player sees the party's sheets and the goblins across the room, not their hit points.
player = session.view(Visibility.PLAYER)
for member in player.party:
    print(member.name, member.current_hp, member.max_hp)
# Hild 3 3
group = player.encounter.groups[0]
print(group.label, group.count, group.distance_feet)
# goblin 2 30

# The referee sees each monster's hit points.
referee = session.view(Visibility.REFEREE)
print([monster.current_hp for monster in referee.monsters])
# [1, 3]

EdgeView

Bases: BaseModel

One visible edge: what occupies it, and a door's state.

You get these from ExploredLevelView.edges. An undiscovered secret door appears as a wall, so if you draw what the view contains, you never reveal one.

kind instance-attribute

kind: str

What occupies the edge: "open", "wall", or "door", the serialized values of EdgeKind. For an undiscovered secret door, it's "wall". On a cell side that has a passage, it's "open". A passage is a level transition that leads through a wall: the level's edges have a wall there, but a MoveParty across that side takes the party to the passage's destination.

door_open class-attribute instance-attribute

door_open: bool | None = None

Whether the door stands open. None on an edge that is not a door.

door_wedged class-attribute instance-attribute

door_wedged: bool | None = None

Whether the door has been wedged with an iron spike. None on an edge that is not a door.

EncounterGroupView

Bases: BaseModel

A monster group as the players see it: what it is, how many, how far, how it looks.

You get these from EncounterView.groups. Hit points and other statistics never appear, because the players know only what they can see across the room.

id instance-attribute

id: str

The group's id, like "group-0001". You put it in the target_group_id of a battle declaration, so a remote client needs it to fight at all. It's a session id that counts up, not a secret, the same as a MemberView.id.

label instance-attribute

label: str

What to call one member of the group in a sentence, like "goblin". It's the same as EncounterGroup.label, which lists where each kind of group gets its label. It's display text, so don't match on its words. To tell what kind of creature the group is, read family_id and categories.

label_plural class-attribute instance-attribute

label_plural: str = Field(default='', validate_default=True)

What to call two or more members of the group, like "goblins" or "wolves". It's the same as EncounterGroup.label_plural.

family_id class-attribute instance-attribute

family_id: str | None = None

What kind of monster the group is, as the family_id its members' templates share, like "fire_beetle" or "hellhound". None for a party of NPC adventurers, and for a group whose members come from more than one family.

The value is the same however the group came to be: from a keyed area, a wandering monster check, or a SpawnMonsters. So match on it, not on the words in label. Pass it to MonsterCatalog.family to read what the players' rulebook says about the creature.

It reveals no more than the label does. A family is the creature the players see, and it's shared by every form the players can't tell apart, so a group of hellhounds is "hellhound" whatever their Hit Dice.

A group your code opens with start_encounter under a label of its own still reports its templates' family here. To show the players a creature under another name, give it a template of its own in Adventure.monsters. That template is its own family.

categories class-attribute instance-attribute

categories: tuple[str, ...] = ()

The categories every member of the group has, like ("undead",), as in MonsterTemplate.categories. A party of NPC adventurers is ("person",), because hold person and charm person affect any character.

Use it to offer what works only against one kind of creature. Turning and holy water affect a group with "undead", and hold person affects a group with "person".

count instance-attribute

count: int

How many of the group are still alive.

distance_feet instance-attribute

distance_feet: int

How far away the group is on the range track, in feet.

visible_conditions instance-attribute

visible_conditions: tuple[str, ...]

The conditions visible on the living members of the group, as Condition serialized values, sorted and deduplicated so the same condition on six goblins appears once. condition_counts says how many members have each one.

condition_counts class-attribute instance-attribute

condition_counts: dict[str, int] = {}

How many living members of the group have each visible condition, keyed by the condition's serialized value. Its keys are the values in visible_conditions, in the same order.

When sleep takes 4 of 11 orcs, count is 11 and this is {"asleep": 4}, so you can show "4 of 11 orcs asleep" and tell whether a second sleep is worth casting.

fled class-attribute instance-attribute

fled: bool = False

True once the group has run away and left the battle, as in EncounterGroup.fled.

A fled group stays in EncounterView.groups, but the session refuses every declaration aimed at it with battle.declaration.unknown_group. So don't offer it as a target. A group that's running but hasn't got away yet isn't fled. You can still close on it, shoot at it, or cast at it.

member_distance_feet class-attribute instance-attribute

member_distance_feet: dict[str, int] = {}

Each living party member's distance to this group, in feet, keyed by member id. Empty outside a battle.

A battle measures each group's distance_feet from the party line, where the party stood when the encounter opened or where the line has moved back to since, and each member stands at their own advance from that line, in EncounterView.advance_feet. This is the group's distance minus the member's advance. At 5' or less, the member and the group can reach each other in melee. Beyond that, a member attacks the group with a missile weapon, or declares move="close" to move toward it first. A missile's range band and a spell's range are measured from this distance.

front_rank class-attribute instance-attribute

front_rank: tuple[str, ...] = ()

The members who can make a melee attack on this group this round without moving, and whom this group's melee reaches, in marching order. Empty outside a battle, and empty while nobody stands within 5' of the group.

These are the members in the party's front rank toward this group who stand within 5' of it. The ranks toward a group are the living members sorted by their distance to it, nearest first, and cut into rows of EncounterView.formation_width. A row never mixes distances. Arrival order, then marching order, decides who is in the front row, so the member who got there in an earlier round stands in front of one who arrives later. This tuple then lists that row's members in marching order. It's always the same value as group_front_rank for this group.

The session refuses a melee attack on this group by any other member with battle.declaration.not_in_front_rank, or with combat.attack.out_of_reach when the member is farther than 5' away, unless the same declaration's move="close" brings them into it. When this tuple has fewer members than formation_width, a member who can reach the group this round can still take a place in it. preview_battle_round answers that for a plan you're building.

Each of this group's monsters picks its melee target from these members, leaving out invisible members and members whose protection from evil bars it. A monster with a missile attack closes and uses it at 5' too, so the members behind this rank are out of a monster group's reach. NPC adventurers with missile weapons shoot from farther away, at the members in the first row of the party's ranks toward their group.

Only the monsters' front rank makes melee attacks on these members: the group's first living monsters, as many as EncounterView.formation_width. So six skeletons in a 10' corridor strike with two at most, the smaller of count and the width. A monster in front that's asleep, paralysed, or turned to stone keeps its place and doesn't attack, so fewer can strike. condition_counts counts those conditions across the whole group, so it doesn't say whether they fall on the monsters in front. With the ruleset's formation_width_limit flag off, every living monster can attack.

lit class-attribute instance-attribute

lit: bool | None = None

Whether a light the party carries reaches this group, or None outside a battle.

The group is lit when a living member with a burning light, like a torch or a lantern, stands within that light's radius of it, 30' for a torch or a lantern. A darkness effect that puts out the party's light, as GameSession.party_light reports, leaves every group unlit. The session refuses no declaration because a group is unlit, so use this field and seen_by to decide what your game offers or how it describes the fight.

seen_by class-attribute instance-attribute

seen_by: tuple[str, ...] = ()

The living members who can see this group, in marching order. Empty outside a battle.

A member sees the group when it's lit, or when the member has working infravision and the group is within its range. A dwarf's and an elf's infravision reaches 60', and so does infravision an effect grants. A darkness effect that stops infravision, as GameSession.party_light reports, leaves it working for nobody. A blind member sees nothing.

EncounterView

Bases: BaseModel

The current encounter or battle's public state.

You get one from PlayerView.encounter, which is None when the party isn't in an encounter.

In a battle, each party member stands at their own place on the range track, the one-dimensional measure of distance a battle uses. advance_feet gives each member's place, and each group in groups gives every member's distance to it and the members who can reach it in melee. Read those to draw the fight and to offer each member the moves and attacks they can make.

The id tuples declarers, immobile, and reloading describe the battle round as the players see it at the table: who is able to act, who is held fast, and who is still reloading a crossbow. Each group's front_rank says who can attack that group in melee this round. Each of these matches a rejection that would refuse the whole round, so if you read them, you offer only the declarations the session accepts. To check a choice against the choices already made for the round, call preview_battle_round.

groups instance-attribute

groups: tuple[EncounterGroupView, ...]

The monster groups in the encounter, in the order the session's encounter state lists them.

stance instance-attribute

stance: str | None

How the monsters are behaving, as a ReactionResult serialized value: "attacks", "hostile", "uncertain", "indifferent", or "friendly". None before the reaction roll has settled it.

in_battle instance-attribute

in_battle: bool

Whether the encounter has become a battle with rounds and declarations.

battle_round class-attribute instance-attribute

battle_round: int | None = None

The current battle round, counting from the first. None outside a battle.

pursuit_gap_feet class-attribute instance-attribute

pursuit_gap_feet: int | None = None

How far ahead of its pursuers the fleeing party is, in feet. None when the party isn't being pursued.

declarers class-attribute instance-attribute

declarers: tuple[str, ...] = ()

Every member who has to declare this round, in marching order: the ones living and able to act. A ResolveBattleRound with any other roster, a slept or paralysed member included, is rejected whole with battle.declaration.roster_mismatch.

front_rank class-attribute instance-attribute

front_rank: tuple[str, ...] = ()

The first row of the party's ranks toward the nearest group, in marching order.

The nearest group is the group that hasn't fled and has a living member, and that stands closest to any living member. When two are equally near, it's the one that comes first in groups. The ranks toward a group are the living members sorted by their distance to it and cut into rows of formation_width, and this is the first row, however far away it stands. With the ruleset's formation_width_limit flag off, the row holds every living member at the nearest distance. Outside a battle, every member stands on the party line, so it's the party's first rank in marching order.

In a fight with one group, before any member has moved, it's the members who can attack that group in melee once it's within 5'. As soon as members stand at different distances, or the party fights more than one group, read each group's front_rank instead, which says exactly who can attack that group in melee this round.

immobile class-attribute instance-attribute

immobile: tuple[str, ...] = ()

The declarers who can't move this round. In practice they're the entangled members, because the other conditions that stop a move stop every declaration as well. A move declaration of any kind from one of them is rejected with battle.declaration.cannot_move, and so is an attack from one of them that sets move="close".

reloading class-attribute instance-attribute

reloading: tuple[str, ...] = ()

The members who may not fire a reload weapon this round, because they fired one last round (combat.attack.reload). Empty when the ruleset's weapon_reload flag is off, so you can combine this list with the weapon's qualities and never read the flag.

advance_feet class-attribute instance-attribute

advance_feet: dict[str, int] = {}

Each living member's place on the range track, keyed by member id, in feet forward of the party line. Empty outside a battle.

The party line is where the party stood when the encounter opened. Each group's distance_feet is measured from it. Every member starts a battle on the line, at zero. A member who closes on a group moves forward, and a member who falls back alone moves back, below zero once they're behind the line. When every member the monsters can see is behind the line, the line moves back to the foremost of them. This field and each group's distance_feet then show the moved values, and no distance between a member and a group changes. Use it to draw where each member stands. Each group's member_distance_feet gives the distance it leaves between the member and that group.

formation_width class-attribute instance-attribute

formation_width: int | None = None

How many members can fight side by side where the party stands, or None when the ruleset's formation_width_limit flag is off and a rank has no width limit.

The width is the side of the largest square of open cells that includes the party's cell, times 10', divided by 5' for each combatant (FIGHTER_FRONTAGE_FEET). The square holds only cells of the space the party stands in, so a door or the edge of a room bounds it. A one-cell corridor gives 2, and so does a crossroads of one-cell corridors. A room gives twice its shorter side in cells: a 4 by 4 room gives 8, and a 2 by 8 room gives 4. The width comes from the party's cell, so it's set in an encounter before a battle starts, and it stays the same for the whole fight. The ranks toward each group are rows this wide, so a group's front_rank never holds more members than this. Compare the two to show how many places are left in a group's front rank.

The width limits the monsters too. Each group's front rank of monsters is its first living monsters, as many as this, and only they make melee attacks on the party.

party_free_round class-attribute instance-attribute

party_free_round: bool = False

True in the round the party gets free after it surprised the monsters, while the monsters can't act. False in every other round, and outside a battle.

It's the round in which a thief's back-stab is legal: an attack that sets BattleDeclaration.back_stab. It's true while BattleState.monsters_hold_rounds is above zero.

ExplorationCounters

Bases: BaseModel

The exploration counters a session keeps between commands: distance, rest, wandering, noise, sleep, food.

You get one from RefereeView.exploration. These are the counters GameSession keeps as attributes, under the same names, and a save contains them under its exploration key. They're for the referee, and none of them reaches PlayerView, which reports the party's fatigue, exhaustion, and deprivation as yes-or-no status instead.

odometer_thirds instance-attribute

odometer_thirds: int

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_rest: int

Turns since the party last rested. The fatigue rule counts these, and a Rest resets them.

wandering_counter instance-attribute

wandering_counter: int

Turns since the last wandering-monster check. Reaching the level's interval fires the check and resets this to zero.

noise_since_check instance-attribute

noise_since_check: bool

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.

sleep_count instance-attribute

sleep_count: int

How many nights or days the party has slept through. Preparing spells needs a sleep the caster has not already prepared from.

last_prepared_sleep instance-attribute

last_prepared_sleep: dict[str, int]

The sleep_count at which each caster last prepared spells, keyed by character id. The session uses it to allow one preparation per sleep.

alerted_areas instance-attribute

alerted_areas: tuple[str, ...]

The keyed areas whose monsters have been alerted, as "{dungeon}:{level}:{area}" references. Monsters that heard the party coming are not surprised when it walks in.

heard_areas instance-attribute

heard_areas: tuple[str, ...]

The keyed areas the party has heard something in, as "{dungeon}:{level}:{area}" references. A party that knows what stands behind the door is not surprised by it.

provisions_day instance-attribute

provisions_day: int

How many whole game days of food and water the session has charged the party for, counting from the start of the session. Each time the clock passes into a new day, the session charges the party for the day and adds one to this.

ExploredLevelView

Bases: BaseModel

One level's explored map: the cells the party knows, and the edges around them.

You get these from PlayerView.explored, one for each level the party knows anything about. This is the map to draw. The party knows nothing outside it.

dungeon_id instance-attribute

dungeon_id: str

The id of the dungeon this level belongs to.

level_number instance-attribute

level_number: int

The 1-based level number.

cells instance-attribute

cells: tuple[Position, ...]

The known cells as (x, y) pairs: the cells the party has walked, then the cells it remembers having seen, then the cells its light shows from where it stands right now. When a member lights a torch, the next view includes the lit room, even if the party hasn't moved.

edges instance-attribute

edges: dict[str, EdgeView]

The edges around those cells, keyed by the canonical edge key that edge_key returns, in the form "{x},{y}:north" or "{x},{y}:west". Each physical edge appears once, so a wall between two known cells is one entry, not two.

MemberEffectView

Bases: BaseModel

One active effect on a party member, like a burning torch or a running spell.

You get these from PlayerView.effects. Only effects on a party member appear. An effect attached to a dungeon cell, like a pool of burning oil, is for the referee and doesn't appear.

character_id instance-attribute

character_id: str

The id of the member the effect is attached to, matching a MemberView.id.

kind instance-attribute

kind: str

The effect kind, like "light" or "fatigue". It's the same string an EffectActiveCondition checks for.

remaining_rounds instance-attribute

remaining_rounds: int | None

Rounds left before the effect expires, never below zero. None when the effect has no expiry, and for any effect a potion gave, because by the rules the referee tracks a potion's duration and never tells the players.

MemberView

Bases: BaseModel

One party member's character sheet, as the players see it.

You get these from PlayerView.party, in marching order, and every party member has one, living or dead. The players know everything about their characters, so the view has every number on a B/X character sheet, and a client can draw the sheet from it alone. The only thing missing is the identity of an unidentified magic item in the pack.

The numbers are the member's current ones, read from the live Character. They count what the member wears right now, like armour, a shield, or a ring of protection. They don't count a timed effect from a spell or a potion, like the shield spell. PlayerView.effects lists the timed effects on each member.

A STR that an item sets counts too. A member who wears gauntlets of ogre power has the numbers for STR 18. Six rounds after a member puts on a ring of weakness, the ring's curse takes hold, and the member has the numbers for STR 3. Either way, effective_strength, melee_modifier, and open_doors_chance change, and scores still shows the rolled STR.

id instance-attribute

id: str

The member's character id, like "character-0001". It's the id you put in the character_id of a command like GrantItem or a battle declaration, so a remote client can issue commands without having the session.

name instance-attribute

name: str

The character's name, as the player wrote it.

class_id instance-attribute

class_id: str

The character class id, like "fighter", as in Character.class_id. For a class your game wrote, it's the id of the character's custom_class, so look the class's name up in your own definitions.

level instance-attribute

level: int

The character's experience level.

current_hp instance-attribute

current_hp: int

Current hit points. Zero or less means the member is down, and conditions shows what took them out.

max_hp instance-attribute

max_hp: int

Maximum hit points at the current level.

conditions instance-attribute

conditions: tuple[str, ...]

The conditions on the member right now, as Condition serialized values like "dead" or "asleep", in the order the member gained them.

inventory instance-attribute

inventory: dict

The member's pack, as a JSON-ready dict with the keys items, purse, valuables, worn_armour, shield, wielded, and rings. Mundane items appear as the inventory serializes them.

A magic item is masked until it's identified. An unidentified one has a display name in place of its true name, like "a potion", or "a dagger with a faint aura" for a magic weapon. When the display name refers to a weapon, the entry also has the qualities of that plain weapon, as an identified one does, so you can tell a melee attack from a missile attack without revealing the weapon's bonus or curse. It has a missile_ranges key only when the rules give the weapon ranges, so on a sword the key is absent rather than empty. Every magic staff displays as "a staff" and has the staff's qualities. Any other item whose display name comes from its category, like "a wand", has neither key, because its display name doesn't refer to a weapon. An identified item shows its name, its template_id, and whether a curse has been revealed. Charges never appear.

memorized_spells instance-attribute

memorized_spells: tuple[dict, ...]

The prepared spells, one dumped MemorizedSpell per copy, in memorization order. Empty for a class that casts nothing.

encounter_rate_feet class-attribute instance-attribute

encounter_rate_feet: int = 0

How far the member can move in one round of a battle or an encounter, in feet.

It's a third of the member's movement rate after encumbrance, doubled while haste is on them. In a battle, a member who declares move="close" moves up to this far toward the group, and stops 5' from it. So a member can close on a group and attack it in the same round when their distance to it, in EncounterGroupView.member_distance_feet, is at most this rate plus 5'. Use it to offer "close in and attack" only to the members who can reach.

It doesn't account for conditions. A member who can't move this round, like one held by a web, still has a rate here, and EncounterView.immobile lists them.

race class-attribute instance-attribute

race: str = ''

The character's race id, like "human" or "dwarf", as in Character.race.

alignment class-attribute instance-attribute

alignment: str = ''

The character's alignment, as an Alignment serialized value: "lawful", "neutral", or "chaotic".

title class-attribute instance-attribute

title: str | None = None

The level title, like "Veteran" for a 1st-level fighter, as level_title returns it. None past the last title the class has, so show the class name instead.

xp class-attribute instance-attribute

xp: int = 0

The experience points the character has.

xp_next_level class-attribute instance-attribute

xp_next_level: int | None = None

The experience points the next level needs, or None when the character has reached the highest level of the class.

scores class-attribute instance-attribute

scores: dict[str, int] = {}

The six ability scores, keyed by AbilityScore serialized value: "str", "int", "wis", "dex", "con", and "cha".

They're the scores the character rolled, as in Character.scores. A STR that an item sets, like the 18 of gauntlets of ogre power, changes effective_strength but not "str".

effective_strength class-attribute instance-attribute

effective_strength: int = 0

The STR score the rules use during play, as Character.effective_strength gives it. melee_modifier and open_doors_chance come from it.

It's scores["str"] unless an item sets the member's STR. So a fighter who rolled STR 11 and wears gauntlets of ogre power has 18 here and 11 in scores. To show a player what the item did, show both numbers. Like the armour class, it counts the gauntlets before the party identifies them, while inventory still shows them as "a curious device".

melee_modifier class-attribute instance-attribute

melee_modifier: int = 0

The Strength modifier to melee attack rolls and melee damage, as Character.melee_modifier. It's the modifier combat adds.

It comes from effective_strength, not from scores["str"]. So a fighter with STR 11 who wears gauntlets of ogre power has +3 here.

missile_modifier class-attribute instance-attribute

missile_modifier: int = 0

The Dexterity modifier to missile attack rolls, as Character.missile_modifier.

initiative_modifier class-attribute instance-attribute

initiative_modifier: int = 0

The Dexterity modifier to the member's initiative roll, as Character.initiative_modifier. The session uses it only under individual initiative.

hit_point_modifier class-attribute instance-attribute

hit_point_modifier: int = 0

The Constitution modifier to each Hit Die rolled, as Character.hit_point_modifier.

magic_save_modifier class-attribute instance-attribute

magic_save_modifier: int = 0

The Wisdom modifier to saving throws against magic, as Character.magic_save_modifier.

npc_reaction_modifier class-attribute instance-attribute

npc_reaction_modifier: int = 0

The Charisma modifier to reaction rolls, as Character.npc_reaction_modifier.

open_doors_chance class-attribute instance-attribute

open_doors_chance: int = 0

The chance in 6 of forcing a stuck door open, as Character.open_doors_chance. It's the chance the session rolls against for a ForceDoor, and it comes from effective_strength.

thac0 class-attribute instance-attribute

thac0: int = 0

The d20 roll the member needs to hit armour class 0, as Character.thac0. Show it when your game uses descending armour class.

attack_bonus class-attribute instance-attribute

attack_bonus: int = 0

The bonus the member adds to an attack roll against ascending armour class, as Character.attack_bonus.

armour_class class-attribute instance-attribute

armour_class: int = 0

The member's descending armour class, where lower is better, as Character.armour_class.

It counts everything the member wears, unidentified magic items included, because it's the armour class the monsters roll against. So the armour class can show that a shield is better than a plain one while inventory still calls it "a shield with a faint aura".

armour_class_ascending class-attribute instance-attribute

armour_class_ascending: int = 0

The member's ascending armour class, where higher is better, as Character.armour_class_ascending. It counts the same items as armour_class.

saves class-attribute instance-attribute

saves: dict[str, int] = {}

The five saving throws, keyed by the field names of SavingThrows: "death", "wands", "paralysis", "breath", and "spells". Each value is the d20 roll the member needs, as Character.saves gives it.

movement_rate_feet class-attribute instance-attribute

movement_rate_feet: int = 0

How far the member moves in one exploration turn, in feet, as Character.movement_rate returns it under the session's ruleset. The party moves at the rate of its slowest living member.

languages class-attribute instance-attribute

languages: tuple[str, ...] = ()

The ids of the languages the member speaks, as Character.languages lists them.

spell_book class-attribute instance-attribute

spell_book: tuple[str, ...] = ()

The ids of the spells in the member's spell book, as in Character.spell_book. They're the spells the member can choose from in a PrepareSpells. Empty for a class that has no spell book.

thief_skills class-attribute instance-attribute

thief_skills: dict[str, int] = {}

The member's chance at each thief skill at their level, keyed by the skill field names of ThiefSkillRow, like "open_locks" and "move_silently". "hear_noise" is a chance in 6, and every other skill is a percentage. Empty for a class that has no thief skills.

ObjectiveView

Bases: BaseModel

One revealed objective as the players know it: what it's called, and whether it's done.

You get these from QuestView.objectives. An objective the players haven't been told about is absent from the list, not listed as unknown, so state has only the two values a revealed objective can have. The adventure defines the objective in an ObjectiveSpec, and the session tracks it in an ObjectiveState. A remote client has neither.

id instance-attribute

id: str

The objective's id, unique within its quest.

name instance-attribute

name: str

The objective's display name: its name in the adventure, or its id when the adventure gives it no name. It's never empty.

state instance-attribute

state: str

"incomplete" or "complete".

PileView

Bases: BaseModel

A known dropped pile in explored space.

You get these from PlayerView.piles, keyed by cell reference. A pile in a cell the party has not walked is left out, so the view never shows the players loot they haven't found.

items instance-attribute

items: tuple[str, ...]

One display string per thing in the pile, in the order mundane items, magic items, then valuables. A mundane entry has the form "{item_id}×{quantity}". A magic item shows its name once identified and its masked display name before that. A valuable shows its name, or its kind when it has no name.

coins_gp_value instance-attribute

coins_gp_value: int

The pile's coins, as their value in whole gold pieces, rounded down.

PlayerView

Bases: BaseModel

What a player may see of a session: a fixed list of fields, every one safe to show.

Get one from GameSession.view with Visibility.PLAYER, or from build_player_view. In a networked game, send this object to a player's client. Every field is safe to show at the table, and it contains only what the party has learned. Get a new one after every command, because a view is a frozen snapshot that doesn't change.

adventure_name instance-attribute

adventure_name: str

The adventure's title.

adventure_description instance-attribute

adventure_description: str

The adventure's description, for a title screen.

town_name instance-attribute

town_name: str

The base town's name.

town_description instance-attribute

town_description: str

The base town's description.

town_services instance-attribute

town_services: tuple[str, ...]

The services the town offers, as text from the adventure for you to list.

town_healing_prices class-attribute instance-attribute

town_healing_prices: dict[str, int] = {}

What the town's temple charges for each of its services, in gold pieces, keyed by the HealingService name, like "raise_dead". Every service is listed. A price comes from TownSpec.healing_prices where the adventure sets one, and from the standard prices in HEALING_SERVICES otherwise. Read it to show the temple's price list, and to check the party's gold against a price before you send a PurchaseHealing.

party instance-attribute

party: tuple[MemberView, ...]

The party's character sheets, in marching order, the dead included.

location instance-attribute

location: PartyLocation

Where the party is: the town, or a dungeon cell with its facing.

clock_rounds instance-attribute

clock_rounds: int

How much game time has passed since the session began, in rounds.

mode instance-attribute

mode: str

The session mode as a SessionMode serialized value: "town", "exploring", "encounter", "battle", "game_over", or "victory". Read it to decide which commands to offer, because each mode accepts different commands.

explored instance-attribute

explored: tuple[ExploredLevelView, ...]

The party's map, one entry per level it knows anything about.

piles instance-attribute

piles: dict[str, PileView]

The dropped piles the party knows about, keyed by the cell reference cell_ref returns. A pile in a cell the party has not walked is left out.

emptied_caches instance-attribute

emptied_caches: tuple[str, ...]

The treasure caches the party has already emptied, as "{dungeon}:{level}:{id}" references, so you can draw a looted cache as looted.

effects instance-attribute

effects: tuple[MemberEffectView, ...]

The active effects on party members, in ledger order.

fatigued instance-attribute

fatigued: bool

Whether any member is fatigued.

exhausted instance-attribute

exhausted: bool

Whether any member is exhausted.

deprivation instance-attribute

deprivation: dict[str, dict[str, int]]

Food and water deprivation, keyed by character id, each value containing food_days and water_days. A member with no deprivation on either track is left out, so an empty dict means the party has been eating and drinking.

journal instance-attribute

journal: tuple[JournalEntry, ...]

The session journal, the players' record of the adventure, in the order the entries were written. Each entry has the clock time when it was written. The record of which triggers fired, and the referee's notes, stay out.

quests instance-attribute

quests: tuple[QuestView, ...]

The active quests, in the order the adventure lists them. A quest the party hasn't taken on yet is left out. A finished quest leaves the list, and the journal still contains every entry it added.

encounter class-attribute instance-attribute

encounter: EncounterView | None = None

The current encounter or battle's public state, or None when the party is not in one.

QuestView

Bases: BaseModel

One active quest as the players know it: the task, who gave it, and where it stands.

You get these from PlayerView.quests. The rules that start a quest, complete it, and reward it never appear, because they're hidden from the players the same way a trigger's rules are. When you have the session, read the quest's definition from QuestSpec and its state from QuestState.

id instance-attribute

id: str

The quest's id in the adventure.

name instance-attribute

name: str

The quest's display name.

narrative instance-attribute

narrative: str

The adventure's text for offering the quest, its narrative's offer, or the empty string when it has none. The view includes the text because a remote client has no adventure document to look it up in.

speaker instance-attribute

speaker: str

Who speaks the offer, like "Sister Halda", or the empty string when the adventure gives no speaker.

objectives instance-attribute

objectives: tuple[ObjectiveView, ...]

The revealed objectives, in the order the quest lists them.

RefereeView

Bases: BaseModel

The full state of a session except the random streams, one typed field for each group of data in a save.

Get one from GameSession.view with Visibility.REFEREE, or from build_referee_view. Use it where players can't see it: as the context an LLM referee reasons over, in a debugging panel, or in a test that checks state a player may not see. Never send it to a player's client, and draw nothing a player sees from it. PlayerView is for that.

Each field is the session's model rather than a dict, so you read view.monsters[0].current_hp and view.flags["key"] with the types this reference documents, and each field's docstring links the model to read next. The fields are the groups session_state writes, minus the master seed and the RNG stream positions, so view.model_dump(mode="json") is that save payload without those two keys. The seed and the stream positions live only in the save, because knowing them would let a player predict every roll to come.

The view is a snapshot of the moment it was built. The session's mutable state is copied into it, so later play leaves the view as it was, and editing what you find on a view changes nothing on the session. Being frozen fixes the view's fields rather than their contents, so rebinding view.flags raises while view.flags["key"] = 1 and view.monsters[0].current_hp = 0 edit the view's copies and are allowed. Build a fresh view after each command rather than editing one. The command log, the event log, and the journal are shared with the session instead of copied, because a command, an event, and a journal entry are frozen records of something that has already happened.

ruleset instance-attribute

ruleset: Ruleset

The options this session plays under, as a Ruleset, whose flags turn the optional rules on and off.

party instance-attribute

party: Party

The party, as a Party of full Character sheets in marching order, the dead included. Every number is here, the spell book and the true names of magic items among them, so render a player's sheet from PlayerView.party instead, which masks what the party has not identified.

adventure instance-attribute

adventure: Adventure

The whole adventure document, as an Adventure: the town, the dungeons with their complete geometry and keyed areas, the triggers, and the quests. It is the map with nothing hidden, so draw the party's map from PlayerView.explored instead. The document is frozen and the view copies it even so, because the tree under it contains dicts you can edit in place, the town's travel turns and each level's edges among them.

mode instance-attribute

The SessionMode the session is in. The mode sets which commands the session accepts right now.

clock_rounds instance-attribute

clock_rounds: int

How much game time has passed since the session began, in rounds.

allocator instance-attribute

allocator: IdAllocator

The source of session ids, as an IdAllocator. It hands out each <kind>-NNNN id by counting up, so two runs of the same commands assign the same ids.

ledger instance-attribute

ledger: EffectsLedger

The active effects, as an EffectsLedger: spells running, conditions, a torch burning down, each with the round it expires at. It includes the effects attached to dungeon cells as well as the ones on members, and the true duration of a potion's effect, which the players aren't allowed to know.

dungeon_state instance-attribute

dungeon_state: DungeonState

What the session has recorded on top of the adventure's map during play, as a DungeonState: where the party stands, the cells it has walked and seen, door state, found and sprung traps, drop piles, and generated caches.

monsters instance-attribute

monsters: tuple[MonsterInstance, ...]

Every monster spawned this session, as MonsterInstance values in the order they were spawned, the defeated ones included, so a later event can still refer to them. Their hit points and other statistics are here. The players see monsters only as EncounterGroupView values.

npcs instance-attribute

npcs: tuple[Character, ...]

The NPC adventurers in play, as Character sheets in the order they joined. They are characters rather than monsters, and they fight by the same rules as the party.

flags instance-attribute

flags: dict[str, str | int | bool]

The session flags: the key-value store that SetFlag writes and an adventure's triggers, quests, and door and exit conditions read. Flags are part of the adventure's hidden rules, so no flag ever reaches a player view.

fired_triggers instance-attribute

fired_triggers: tuple[str, ...]

The ids of the triggers that have fired, in the order they first fired. Use it to check whether a trigger has fired before. It's for the referee only. The players learn what a trigger did from the journal entry it added, if any.

journal instance-attribute

journal: tuple[JournalEntry, ...]

The journal, as JournalEntry values in the order they were written. The players see the same list, and you read it for them from PlayerView.journal.

quests instance-attribute

quests: dict[str, QuestState]

The state of every quest in the adventure, as QuestState values keyed by quest id, in the order the adventure lists them. It includes the inactive and completed quests as well as the active ones, and every objective, revealed or hidden. The players' version is PlayerView.quests.

listener_state instance-attribute

listener_state: dict[str, dict]

Each registered listener's state, keyed by the listener's key, as that listener's handle returned it. The session stores it and never reads it, so the listener decides what it means.

death_records instance-attribute

death_records: dict[str, DeathRecord]

When and how each dead party member died, as DeathRecord values keyed by character id. When the engine resolves raise dead, it reads the day count from here, and for neutralize poison, the round window.

defeated_monsters instance-attribute

defeated_monsters: tuple[DefeatedMonsterRecord, ...]

The creatures defeated since the last experience award, as DefeatedMonsterRecord values in the order they fell. GameSession.award_adventure_xp adds up their xp and clears the list.

deprivation instance-attribute

deprivation: dict[str, DeprivationState]

The food and water counts, as DeprivationState values keyed by character id. There's one for each member the session has charged for food and water at the start of a new day, including members whose counts are zero. PlayerView.deprivation reports the same counts, but only for members whose counts aren't zero.

treasure_snapshot_cp instance-attribute

treasure_snapshot_cp: int | None

What the party's treasure was worth in copper pieces when it left town, or None when no delve is under way. The adventure award pays for the difference between this and what comes back.

exploration instance-attribute

exploration: ExplorationCounters

The exploration counters, as ExplorationCounters: distance walked, turns since a rest, turns since a wandering check, noise, sleep, and food.

encounter instance-attribute

encounter: EncounterState | None

The encounter under way, as an EncounterState, or None when nothing is happening. It contains each group's monster ids, its distance, the stance the reaction roll settled, and any chase in progress. The players' reading of the same encounter is PlayerView.encounter.

battle instance-attribute

battle: BattleState | None

The battle under way, as a BattleState, or None outside one. It contains the round number and the state that persists from round to round, including who fired a weapon that needs reloading last round.

command_log instance-attribute

command_log: tuple[SerializeAsAny[Command], ...]

Every accepted command, in order, each one the Command subclass it was issued as, so its fields are there to read. Refused commands are absent, because they changed nothing, and replay_game re-executes this list from the master seed to rebuild the session.

event_log instance-attribute

event_log: tuple[SerializeAsAny[Event] | dict, ...]

Everything that has happened, in order, each entry the Event subclass that was emitted, including the referee-visibility events a player never sees. An entry restored from a save whose event type this library has no class for stays the raw mapping it arrived as, so check for a dict before reading an entry's attributes.

build_player_view

build_player_view(session) -> PlayerView

Build the player view of a session from its current state, never from the event log.

GameSession.view with Visibility.PLAYER calls this function and returns the same view, so you usually call that method instead. Build a view after each accepted command, and render it. Send the view, never the session, to a client you don't control.

The call reads the session and changes nothing, so building a view twice gives two equal snapshots and costs the party no game time.

Parameters:

Name Type Description Default
session GameSession

The running session.

required

Returns:

Type Description
PlayerView

A frozen PlayerView that contains only what the party has learned.

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.crawl.views import build_player_view

rules = Ruleset()
rng = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=rng,
)
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.character]), adventure, seed=7)

player = build_player_view(session)
print(player.mode)
# town
print(player.party[0].id)
# character-0001
assert "flags" not in player.model_dump()  # a player view never includes the session flags

build_referee_view

build_referee_view(session) -> RefereeView

Build the referee view: every group of data in a save, typed, except the seed and the random streams.

Use it for the context an LLM referee reasons over, for a debugging panel, or for a test that checks state a player may not see. GameSession.view with Visibility.REFEREE calls this function and returns the same view, so you usually call that method instead. Never send the result to a player's client. build_player_view is for that. To store a session rather than read it, call save_game, which includes the seed and the stream positions a restored game needs.

The call reads the session and changes nothing. It returns a snapshot, not a live window onto the session. The session's mutable models are copied into it, so later play leaves the view as it was, and editing what you find on the view changes nothing on the session. A frozen model whose containers cannot be edited goes in as it is, which covers the ruleset, the commands, the events, the journal entries, and the death and defeat records. The adventure is frozen as well and is copied anyway, because the authored tree contains dicts you can edit in place, the town's travel turns and each level's edges among them.

Parameters:

Name Type Description Default
session GameSession

The running session.

required

Returns:

Type Description
RefereeView

A frozen RefereeView of the whole session, except the master seed and the random streams' positions.

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 SetFlag
from osrlib.crawl.dungeon import DungeonSpec, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession
from osrlib.crawl.views import build_referee_view

rules = Ruleset()
rng = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hero = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=rng,
)
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.character]), adventure, seed=7)
session.execute(SetFlag(key="gate_raised", value=True))

referee = build_referee_view(session)
print(referee.mode, referee.clock_rounds)
# town 0
print(referee.party.members[0].id, referee.party.members[0].current_hp)
# character-0001 3
print(referee.flags)  # flags never reach a player view
# {'gate_raised': True}