Skip to content

osrlib.crawl.encounter

Decide whether and how a fight starts: surprise, distance, reaction, parley, evasion, pursuit.

An encounter is the part of play between the moment the party and a group of monsters notice each other and the first blow. The functions in this module open an encounter, run it round by round, and close it. They work on a GameSession whose party is in a dungeon, with monster instances the session has already spawned. When a fight starts, osrlib.crawl.battle takes over.

start_encounter opens an encounter and puts the session in encounter mode. From there, you drive it with the encounter commands:

  • Parley and Wait each take one encounter round (10 seconds of game time), and then the monsters act according to their stance, their attitude toward the party, described below. During a chase, Wait runs one round of the chase instead.
  • Evade ends the encounter, or starts a chase when the monsters pursue.
  • TurnUndead ends the encounter when every monster is turned or destroyed, and otherwise starts a battle.
  • EngageBattle starts a battle.
  • EndEncounter ends the encounter when the party talks its way past or walks away. It's a referee command, one your game logic issues rather than a player.

end_encounter closes the encounter and puts the session back in exploring mode.

You rarely call start_encounter yourself. The session opens an encounter the same way for the SpawnMonsters and SpawnNpcParty commands, for the wandering-monster check, and when the party enters a keyed area, an AreaSpec the adventure describes, that has monsters. Call it directly when your own code decides that a group has just come into view. When you send a SpawnMonsters while an encounter is open, the session doesn't open another encounter. The new group joins the open encounter instead, and rolls no surprise or reaction.

Each group has a label and a label_plural to show the players, like "goblin" and "goblins". The label is display text. To tell what kind of creature a group is, read EncounterGroupView.family_id in the player view.

You follow the encounter through events from osrlib.crawl.events:

The reaction roll is reported as a ReactionRolledEvent that only the referee sees. start_encounter also reports an EffectAttachedEvent for each monster that regenerates, like a troll. Only the referee sees those too.

The stance is the monsters' current attitude toward the party, set by the reaction roll on 2d6. The OSE SRD leaves what each result means in play to a human referee, so osrlib applies these rules:

  • 2 or less: the monsters attack at once.
  • 3 to 5, hostile: the monsters attack at the end of the next encounter round, unless the party has started to evade or a parley has improved the stance.
  • 6 to 8, uncertain: the monsters wait. At the end of each encounter round, osrlib rolls the reaction again with no modifier. A Parley also rolls it, once, with the speaker's CHA modifier, before its round ends.
  • 9 to 11, indifferent: the party can pass, parley, or leave.
  • 12 or more: the monsters are friendly.

Only attacking and hostile monsters pursue a party that evades. The OSE SRD leaves pursuit to the referee, so basing it on the reaction is an adaptation: a place where osrlib chooses one interpretation of a rule the SRD leaves open. The adaptations register lists each one.

When start_encounter rolls the distance, it rolls 2d6 × 10 feet and caps the result at the longest straight line of sight from the party's cell. In a room, that's the room's span. In a corridor, it's the length of the corridor, whatever the light. The SRD calls for the roll only "if there is uncertainty", and osrlib treats the walls around the party as settling that uncertainty. A distance you pass in distance_feet isn't capped.

The members of this module, in the order you're likely to need them:

Typical usage:

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, Parley, SessionMode, SpawnMonsters
from osrlib.crawl.dungeon import DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession

rules = Ruleset()
draw = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=draw,
).character
level = LevelSpec(
    number=1,
    width=2,
    height=1,
    entrance=(0, 0),
    edges={"1,0:west": Edge(kind=EdgeKind.OPEN)},
)
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[hild]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))

# Spawning a group opens the encounter, which rolls surprise and reaction here.
session.execute(SpawnMonsters(template_id="goblin", count_fixed=2, distance_feet=30))
assert session.mode is SessionMode.ENCOUNTER
assert session.encounter.stance == "indifferent"  # seed 7 rolls a reaction of 10 on 2d6
assert session.encounter.groups[0].distance_feet == 30

# Parley takes one encounter round and rolls the reaction again with Hild's CHA modifier.
result = session.execute(Parley(character_id=hild.id))
assert result.accepted
assert session.encounter.round == 1

PURSUIT_ROUND_CAP module-attribute

PURSUIT_ROUND_CAP = 30

The chase round at which the pursuers give up and the party gets away, exhausted.

A chase usually ends before this round. Either the gap closes to 5 feet and the pursuers catch the party, which starts a battle, or treasure or food the party drops distracts them. When the party runs exactly as fast as its pursuers, the gap never changes, and this cap ends the chase. At the cap, every living member who isn't already exhausted gets the exhausted condition (-2 to attack and damage rolls, and attackers get +2 to hit them), with an ExhaustionEvent. The session then emits a PursuitEvent with the code encounter.pursuit.escaped and closes the encounter with the outcome "escaped".

The cap isn't a ruleset setting, so every chase uses the same cap. To end a chase sooner, send EndEncounter with the outcome "departed".

EncounterGroup

Bases: BaseModel

One monster group in an encounter: its members, its distance, and the treasure it carries.

You get these from session.encounter.groups. The session creates them when an encounter opens, or when a SpawnMonsters adds a group to it. It updates them during the battle, and loading a save restores them, so you don't construct one yourself. Much of a fight works by group instead of by monster. When a group fails its morale check, the whole group flees at once. A party member's attack names its target group in the target_group_id of a BattleDeclaration.

id instance-attribute

id: str

The group's id, like group-0001. The session assigns it, and it's unique within the session. A battle declaration's target_group_id refers to this id.

label instance-attribute

label: str

What to call one member of the group in a sentence, like "goblin" or "giant centipede".

A group the session makes from monster templates gets their display_name: a keyed group, a group from SpawnMonsters, and a wandering group. A wandering group whose members come from more than one family gets the encounter table row's name instead. A party of NPC adventurers is "adventurer". A group you open with start_encounter gets the label you pass.

It's display text, so don't match on its words. To tell what kind of creature a group is, read EncounterGroupView.family_id.

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 comes from where label comes from: the templates' display_name_plural, or "adventurers". A wandering group whose label is the encounter table row's name gets the row's name here too, because the author of a row with several kinds of creature writes its name for the whole band, like "Tomb guardians". A label you pass to start_encounter gets the templates' plural when it's their display name. Any other label you pass gets the regular English ending that display_name_plural describes, and so does a group loaded from a save that has no plural.

monster_ids class-attribute instance-attribute

monster_ids: list[str] = Field(min_length=1)

The members' ids in the order they were spawned. Pass an id to GameSession.combatant to get the monster. Dead members stay in the list, so check each monster for the dead condition to find the living ones.

distance_feet class-attribute instance-attribute

distance_feet: int = Field(ge=0)

The distance between the party line and this group, in feet. The party line is where the party stood when the encounter opened. In a battle, each member stands at their own advance from that line, in BattleState.advance_feet, and monsters close at their encounter movement rate until they're within MELEE_RANGE_FEET of the nearest member they can see. A routed group moves away. When every member the monsters can see has fallen back behind the line, the line moves back to the foremost of them, and every group's distance grows by the same amount, as BattleState.advance_feet describes.

fleeing class-attribute instance-attribute

fleeing: bool = False

True once the group has failed a morale check and turned to run. Until it gets away, the party can still attack it.

fled class-attribute instance-attribute

fled: bool = False

True once the group has run past FLEE_EXIT_FEET and left the fight, or when its morale score is 2 and it ran as it entered the battle. The session refuses every battle declaration aimed at the group, whether an attack, a move to close, an item, or a spell, with battle.declaration.unknown_group.

member_treasure class-attribute instance-attribute

member_treasure: dict[str, TreasureBundle] = {}

The treasure each member carries, keyed by monster id. The session rolls it when it spawns the monster, from the treasure types for individuals (P through T). When the encounter closes, a slain member's treasure drops on the party's cell, and a routed member takes its treasure away.

group_treasure class-attribute instance-attribute

group_treasure: TreasureBundle | None = None

The treasure the group shares, rolled at spawn from the treasure types for groups (U and V), or None when the group has none. It drops on the party's cell only when every member is slain. If any member routed, the group's treasure goes with the runners. When a turning turns only some members of a group, the group's treasure stays with the members who fight on.

EncounterState

Bases: BaseModel

An open encounter: the monster groups, the stance, the surprise result, and any chase.

You get this from session.encounter, which is None whenever no encounter is open. A save contains it with the session, so a saved game restores in the middle of an encounter. Read it to show the encounter, and change it only through commands: the session's encounter and battle commands update its fields.

kind instance-attribute

kind: str

How the encounter started: "wandering" from the wandering-monster check, "keyed" from an area the adventure placed monsters in, or "spawned" from a referee command.

area_ref class-attribute instance-attribute

area_ref: str | None = None

The keyed area's reference, when kind is "keyed". When every monster in the encounter is slain or routed, end_encounter marks the area's encounter resolved, so entering the area again doesn't start another fight. When the party gets past the monsters some other way, EndEncounter with resolve_area=True marks it resolved too.

groups class-attribute instance-attribute

groups: list[EncounterGroup] = Field(min_length=1)

The monster groups, each an EncounterGroup, in the order they were spawned. There's always at least one.

stance class-attribute instance-attribute

stance: str | None = None

The monsters' current attitude toward the party, as a ReactionResult value: "attacks", "hostile", "uncertain", "indifferent", or "friendly". It's None only while the encounter opens, before the reaction is rolled.

round class-attribute instance-attribute

round: int = 0

The number of encounter rounds run so far. Wait and Parley each add one when the encounter goes on. A chase counts its rounds in pursuit instead.

started_round instance-attribute

started_round: int

The session clock's round count when the encounter opened. end_encounter uses it to make the encounter cost at least one turn.

party_surprised class-attribute instance-attribute

party_surprised: bool = False

True when the party lost the surprise roll and gave up a round.

monsters_surprised class-attribute instance-attribute

monsters_surprised: bool = False

True when the monsters lost the surprise roll. When both sides are surprised, neither side gains anything.

monsters_skip_rounds class-attribute instance-attribute

monsters_skip_rounds: int = 0

The rounds the monsters still have to sit out because they were surprised. Each round they sit out reduces it by one. A battle that starts while any remain gives the party a free round.

hostile_deadline class-attribute instance-attribute

hostile_deadline: int | None = None

The encounter round at which hostile monsters attack. The session sets it each time the stance becomes hostile, and it's None until then. It applies only while the stance is hostile, so once a parley improves the stance, the deadline no longer applies.

evading class-attribute instance-attribute

evading: bool = False

True once the party has tried to evade. While it's True, hostile monsters don't attack at hostile_deadline.

pursuit class-attribute instance-attribute

pursuit: PursuitState | None = None

The PursuitState while a chase is on, or None.

PursuitState

Bases: BaseModel

A chase in progress: the gap between the running party and its pursuers, updated each round.

Read it from session.encounter.pursuit. It's None until a chase starts. A chase starts when the party evades with Evade and an attacking or hostile group runs at least as fast as the party. It also starts when the whole party retreats from a battle and a monster group is still able and willing to follow. During a chase, the session rejects Parley and TurnUndead, and Wait runs one round of the chase. EngageBattle turns the party to fight at the current gap.

round class-attribute instance-attribute

round: int = 0

The number of chase rounds run so far. The first round sets it to 1. The party escapes when it reaches PURSUIT_ROUND_CAP.

gap_feet class-attribute instance-attribute

gap_feet: int = Field(ge=0)

The distance between the party and its pursuers, in feet. It starts at the distance of the nearest pursuing group. When the pursuit follows a retreat from a battle, it starts at the smallest distance from any living member to any group that can follow, after the retreat's move, because members can stand at different places on the battle's range track. Each round, it grows by the party's running rate and shrinks by the running rate of the slowest pursuing group. At 5 feet or less, the pursuers catch the party, and a battle starts.

end_encounter

end_encounter(session, outcome: str) -> list[Event]

Close the open encounter: record defeats, drop loot, release effects, and advance the clock.

You seldom call this yourself. The session calls it when the party wins a battle, evades, escapes a chase, or turns every monster. When the party talks its way past or walks away, send EndEncounter instead. That command calls this function, and the session records the command in the command log, so replay_game reproduces the close. The session doesn't record a direct call to this function, so a replay of the game stays in the encounter.

An encounter must be open when you call it. If session.encounter is None, the function raises ValueError before it changes anything or draws from a random number stream. When it returns, session.encounter is None. If the session was in encounter or battle mode, it's now in exploring mode.

A battle on the encounter ends with it, so when it returns, session.battle is None too. The function emits no BattleEndedEvent for that battle. The EncounterEndedEvent reports the end of both.

Every monster that ended slain or routed gets a MonsterDefeatedEvent and a record in session.defeated_monsters with its experience value. Routed covers three cases: a monster that fled, one that's still fleeing, and one a cleric turned. The function records a defeated NPC adventurer with the template id npc:<class_id>.

The treasure slain monsters carried drops in a pile on the party's cell, which PlayerView.piles shows and TakeTreasure picks up. A slain NPC adventurer drops all its equipment, coins, and magic items too. A LootDroppedEvent lists what went into the pile. When nothing drops, there's no LootDroppedEvent. Routed monsters take their treasure with them. Next, every effect still active on any of the encounter's monsters ends, because the encounter is over. That includes a slain troll's pending revival.

When Ruleset.xp_award_timing is XpAwardTiming.IMMEDIATE, the party gets the experience for the defeated monsters here, and the function clears session.defeated_monsters. Otherwise, the records stay until the party returns to town.

An encounter costs at least one turn (60 rounds). When it closes, the clock advances in two steps:

  1. The clock moves to the start of a turn: the current round if it starts a turn, or else the start of the next turn.
  2. If that's less than 60 rounds after the encounter opened, the clock moves on to 60 rounds after the opening round instead. That can be partway through a turn.

Wandering-monster checks don't run during the encounter. The turn the encounter costs also covers any part of a turn the party had spent walking, so session.odometer_thirds resets to 0.

Parameters:

Name Type Description Default
session GameSession

The running session, with session.encounter set.

required
outcome str

The outcome recorded on the EncounterEndedEvent and shown in its default message text. The session passes "victory", "evaded", "escaped", or "turned", and EndEncounter passes "parley" or "departed". osrlib doesn't check the value, so you can pass any label.

required

Returns:

Type Description
list[Event]

The MonsterDefeatedEvents, the LootDroppedEvent when anything drops, the events of effects ending, the experience award when the ruleset awards it immediately, the EncounterEndedEvent, and the events of the clock advance after it.

Raises:

Type Description
ValueError

If no encounter is open on the session. The session is left as it was, with no draws taken and no time passed.

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 EndEncounter, EnterDungeon, SessionMode, SpawnMonsters
from osrlib.crawl.dungeon import DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession

rules = Ruleset()
draw = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=draw,
).character
level = LevelSpec(
    number=1,
    width=2,
    height=1,
    entrance=(0, 0),
    edges={"1,0:west": Edge(kind=EdgeKind.OPEN)},
)
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[hild]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
session.execute(SpawnMonsters(template_id="goblin", count_fixed=2, distance_feet=30))
opened_at = session.clock.rounds

# The party talks its way clear. The command runs end_encounter and is logged.
result = session.execute(EndEncounter(outcome="parley"))
assert [event.code for event in result.events] == ["encounter.ended"]
assert result.events[0].outcome == "parley"
assert session.encounter is None
assert session.mode is SessionMode.EXPLORING
assert session.clock.rounds == opened_at + 60  # a turn is 60 rounds, and an encounter costs at least one

start_encounter

start_encounter(
    session,
    *,
    groups: list[tuple[str, list]],
    kind: str,
    area_ref: str | None = None,
    distance_feet: int | None = None,
    monsters_roll_surprise: bool = True,
    monsters_aware: bool = False,
    party_aware: bool = False,
    pinned_stance: ReactionResult | None = None
) -> list[Event]

Open an encounter on a session: roll surprise, distance, and reaction, and act on the result.

Call this when your own code decides a monster group has come into view. First spawn the monsters with GameSession.spawn, which adds them to the session, then pass them here as (label, instances) pairs. When this function returns, the session is in encounter mode, and session.encounter is an EncounterState you can read to show the encounter. An attacking stance starts a battle before this function returns, so check session.battle as well as session.mode. From there, drive the encounter with the encounter commands, like Parley and Wait. end_encounter closes it.

When a referee wants a fight on the party's cell, execute SpawnMonsters instead. That command rolls the number of monsters, spawns them, and opens the encounter for you, and the session records it in the command log. Call this function when you need an argument the command doesn't have, like a stance you choose in advance or monsters that can't be surprised. Neither this function nor GameSession.spawn is a command, so the session doesn't record them in the command log. If you call them during play, the game still saves and loads, but replay_game won't reproduce the encounter.

Each side rolls a d6 for surprise, unless something rules the roll out.

The monsters are surprised on a 1 or 2. They don't roll in these cases:

  • monsters_roll_surprise is False. The session passes this for wandering monsters other than an NPC party, because the SRD has them arrive "moving in the direction of the party".
  • monsters_aware is True. The session passes this for a keyed area marked aware, and for an area the party alerted by failing to force a door.
  • The party carries a light.

The party is surprised on a 1 or 2. When the party carries no light and some living member lacks infravision, it's surprised on 1 to 3. That's an adaptation, a place where osrlib chooses one interpretation of a rule the SRD leaves open. The adaptations register lists it as the blind-party adaptation. The party doesn't roll when party_aware is True, which the session passes after a successful listen.

A surprised party faces a basilisk's petrifying gaze as the encounter opens:

  • It applies to a monster whose surprise ability has meets_gaze, as the basilisk's does.
  • Every living party member is affected once. Each saves versus paralysis or turns to stone.
  • It happens at any distance and whatever the stance, even when the monsters are surprised too.
  • A battle that opens from this encounter doesn't repeat it.

The gaze can leave no member standing, so that every member is dead or petrified. Then no round runs. With an attacking stance, the battle that opens ends in defeat at once, before the monsters' free round. With any other stance, the encounter stops at the stance. A command that opens the encounter, like SpawnMonsters, then ends the session in game_over.

A monster whose template has the regeneration ability, like a troll or a thoul, starts to regenerate when this function opens its encounter, and heals in each round that passes. end_encounter stops the regeneration, so a troll that's still dead when the encounter closes stays dead.

Parameters:

Name Type Description Default
session GameSession

The running session. Its party must be in a dungeon, and no encounter may already be open.

required
groups list[tuple[str, list]]

One (label, instances) pair per monster group. label is the group's label, what to call one member in a sentence, like "goblin". Pass the template's display_name to name the monsters as the session would, and the group gets the template's plural too. Any other label gets the regular English plural ending. instances are monster or NPC instances the session has already spawned, as GameSession.spawn returns them.

required
kind str

How the encounter started: "wandering", "keyed", or "spawned". The function stores it in EncounterState.kind.

required
area_ref str | None

The keyed area's reference, when kind is "keyed". When the party slays or routs every monster, the session marks that area's encounter resolved.

None
distance_feet int | None

The starting distance for every group, in feet. With None, the function rolls 2d6 × 10 on the encounter stream and caps the result at the longest line of sight from the party's cell. The function doesn't cap a distance you pass.

None
monsters_roll_surprise bool

False when these monsters can't be surprised, like wandering monsters.

True
monsters_aware bool

True when the monsters already expect intruders. They then don't roll for surprise.

False
party_aware bool

True when the party has heard the monsters, for example by listening at a door. The party then doesn't roll for surprise.

False
pinned_stance ReactionResult | None

A stance to use instead of rolling the reaction, as a ReactionResult. The function doesn't roll a reaction or spend a random draw on one. Pass ReactionResult.ATTACKS to start a battle at once.

None

Returns:

Type Description
list[Event]

The opening events, in the order they happened:

  • An EffectAttachedEvent for each monster that regenerates.
  • A SurpriseRolledEvent for the monsters, and one for the party.
  • The EncounterStartedEvent.
  • When a surprised party faces a gaze, like a basilisk's, each member's saving throw, and the petrification of each member who fails it.
  • The ReactionRolledEvent, unless you passed pinned_stance.
  • The StanceChangedEvent.
  • The events of anything the stance or surprise starts, which can include a battle and its first round. When the gaze left nobody standing, a battle ends as it opens, and no round runs.

Raises:

Type Description
ValueError

If an encounter is already open on the session. The session is left as it was, with no draws taken and no time passed. To add monsters to the open encounter, execute SpawnMonsters.

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.tables import ReactionResult
from osrlib.crawl.adventure import Adventure, TownSpec
from osrlib.crawl.commands import EnterDungeon, SessionMode
from osrlib.crawl.dungeon import DungeonSpec, Edge, EdgeKind, LevelSpec
from osrlib.crawl.encounter import start_encounter
from osrlib.crawl.party import Party
from osrlib.crawl.session import GameSession

rules = Ruleset()
draw = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=draw,
).character
level = LevelSpec(
    number=1,
    width=2,
    height=1,
    entrance=(0, 0),
    edges={"1,0:west": Edge(kind=EdgeKind.OPEN)},
)
crypt = DungeonSpec(id="crypt", name="The Old Crypt", levels=(level,))
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
session = GameSession.new(Party(members=[hild]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))

# Spawn the instances, then run the encounter procedure over them with a stance fixed in advance.
goblins = session.spawn("goblin", 2)
events = start_encounter(
    session,
    groups=[("goblin", goblins)],
    kind="spawned",
    distance_feet=30,
    pinned_stance=ReactionResult.INDIFFERENT,
)
assert [type(event).__name__ for event in events] == [
    "SurpriseRolledEvent",
    "SurpriseRolledEvent",
    "EncounterStartedEvent",
    "StanceChangedEvent",
]
assert session.mode is SessionMode.ENCOUNTER
assert session.encounter.stance == "indifferent"
assert session.encounter.groups[0].monster_ids == ["monster-0001", "monster-0002"]
assert session.encounter.groups[0].label_plural == "goblins"