Skip to content

osrlib.crawl.battle

Run a fight round by round on the range track, with a replaceable policy choosing what the monsters do.

A battle follows an encounter from osrlib.crawl.encounter when a fight starts. The session opens it for you: when the monsters attack, when pursuing monsters catch the party, and when the party executes EngageBattle. Don't call start_battle in normal play. To start a fight, execute EngageBattle. The session is then in battle mode (SessionMode.BATTLE), and session.battle contains a BattleState.

Each round is one ResolveBattleRound command, with one BattleDeclaration for each living party member who can act. A declaration's action is attack, cast, turn_undead, move, use_item, give_item, or hold.

The battle reference uses these terms:

  • Marching order is the order of the party's members, front first, as Party.members lists them. ReorderParty changes it outside a fight.
  • The range track is how a battle measures distance, in the style of The Bard's Tale. Each monster group has a distance in feet from the party line, the place where the party stood when the encounter opened. Each member has an advance, their place in feet forward of that line, in BattleState.advance_feet. When every member the monsters can see has fallen back behind the line, the line moves back to the foremost of them, as advance_feet describes. A member's distance to a group is the group's distance minus the member's advance, and member_distance_feet works it out. A member and a group can fight in melee at MELEE_RANGE_FEET or less.
  • Ranks are the rows the party fights in. The ranks toward a group are the living members sorted by their distance to it, nearest first. Members at the same distance stand in the order they got there, then in marching order. Only the members of the front rank toward a group who stand within 5' of it can fight it in melee, and group_front_rank lists them. Under the Ruleset option formation_width_limit, which is on by default, a rank is as wide as the space the party stands in, divided by FIGHTER_FRONTAGE_FEET. That's two members side by side in a ten-foot corridor, and in a room, as many as the room's shorter side allows. With the option off, every member at the same distance stands in one rank.
  • The monsters' front rank in a group is its first living monsters in the group's order, as many as the same width allows. Only those monsters make melee attacks on the party, and the party's melee attacks on the group reach only them. A monster keeps its place while it lives, even when it can't act, as a party member does in the party's front rank. With formation_width_limit off, every living monster of the group is in it.
  • The formation is the party moving as one body. A fighting_withdrawal or a retreat that every declarer makes is a formation move. Every other move is the declaring member's alone.
  • A declarer is a party member who has to declare an action this round. Every living member who can act is one, and EncounterView.declarers lists them.
  • Surprise gives one side a free round, a round in which the other side doesn't act. The session rolls for surprise when the encounter opens.
  • A group's morale score is a number from 2 to 12, the morale field of the monster's template. When the OSE SRD calls for a morale check, the session rolls 2d6 against it. On a roll over the score, the group fails its morale check and flees. A group with a score of 2 never fights.
  • A concentration spell lasts only while its caster keeps concentrating on it.
  • A declaration fizzles when it fails and has no effect. That happens when the session checks it again just before it resolves, and it no longer passes. A fizzled cast still loses its spell, as a disrupted one does.
  • A pursuit follows when the party runs: the monsters go after it round by round. While one is on, session.encounter.pursuit contains a PursuitState.
  • A draw is one random number taken from a stream, one of the session's named sequences of random numbers (RngStreams). Because the streams are separate, one part of the game never changes the dice another part gets.
  • The effects ledger (EffectsLedger) is the session's record of timed effects, like a spell's, and the conditions they put on creatures.

Several of these rules are adaptations, places where osrlib commits to one reading of a rule the OSE SRD leaves open. The range track is one. The adaptations register lists each one.

There's no command to end a battle. A round ends it in one of three ways:

  • Every party member is dead or turned to stone. The battle and the encounter close, and the session moves to game_over.
  • Every monster group is dead or has fled out of the fight. The battle ends in victory, and end_encounter closes the encounter.
  • The whole party retreats. If no monster group can pursue the party, the encounter closes. Otherwise the session goes back to encounter mode with a pursuit.

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

Between them come the events of the rule functions in osrlib.core: attacks, damage, saving throws, initiative, and morale.

A round follows the OSE SRD's combat sequence:

  1. The party declares. Before anything happens, the session works out where each member's declared move would put them, and judges every declaration against those places. A member who closes and attacks in the same declaration is judged at the distance the close leaves them. If any declaration fails, the session refuses the whole round, and nothing changes.
  2. The spells being cast are announced, and NPC adventurers choose their actions.
  3. Initiative decides which side acts first.
  4. On the party's turn, the session resolves movement, then missile attacks, then magic, then melee. In the movement step, the members who fall back alone move first and the members who close move next, each in marching order. A fighting withdrawal or a retreat that every declarer makes moves the whole formation instead, by moving the groups back. Each missile attack and each spell is measured from where its member stands after the movement step. A melee attack resolves only if the member is within 5' of the group and in its front rank when the attack comes up, or if the group is running and the member was within 5' of it when the round was accepted.
  5. On the monsters' turn, the session checks each group's morale, then resolves the actions each group's policy chose, in order. A group that closes stops within 5' of the nearest member it can see, and its monsters can attack in the same round. A monster's melee attack resolves only when the monster stands in the monsters' front rank, and only against a member in the party's front rank toward the group who stands within 5' of it.
  6. An attack with a weapon that has the slow quality comes last, after both sides have acted. So does a staff's strike for a charge, because a staff is slow.

Every rule is a function in osrlib.core.combat or osrlib.core.spells, like roll_initiative, resolve_attack, and cast_spell. To resolve one rule without a session, call those functions directly, as Using the rules without a session shows.

Each member moves by themselves. A member can close on a group and attack it in the same round, and can fall back alone with a fighting withdrawal or a retreat, as BattleDeclaration.move describes. A group closes until it's within reach of the nearest member it can see, so the members in front keep the monsters off the members behind them. To check a round's declarations before you send them, call preview_battle_round. To draw the battle and offer each member their choices, read the player view's EncounterView: each member's advance, each group's distance from each member, who can reach each group in melee, and which groups each member can see. Two members reach each other when their advances differ by 5' or less. A member has to reach another to hand them an item, to give them a potion to drink, or to touch them with a staff of healing or a touch spell. A touch on a monster follows the rule for melee: the member has to stand in the party's front rank toward the monster's group, and the monster in its group's front rank.

During a round, the session also applies these rules without a command for them:

  • A caster who declared a spell loses it if an attack hits them, or they fail a saving throw, between initiative and their turn to act.
  • A declared melee attack that can't resolve when it comes up fizzles with a DeclarationFizzledEvent at battle.melee.fizzled. That happens when its group has no living monster left to strike, or when the member stands out of reach or out of the group's front rank.
  • Each monster group checks morale when the OSE SRD calls for it.
  • Only the monsters' front rank makes melee attacks on the party, whatever the group's policy chose, so at most as many monsters of a group as the formation width attack in melee in a round. The session skips a melee by any other monster, and a confused monster behind the front rank doesn't attack the party. A monster's missile attack counts as melee, because the session resolves it at 5'. Any monster or NPC adventurer of the group can breathe, gaze, shoot, cast, or drink a potion, as the party's back ranks can shoot and cast.
  • A monster or NPC adventurer that can't act when its action comes up doesn't act, whatever its policy chose. That happens to an NPC adventurer put to sleep after the NPCs chose their actions at the start of the round.
  • When a monster's attack hits, the session applies the effects the attack lists: paralysis, poison, mummy rot, energy drain, petrification, and the spitting cobra's blindness. Each effect gets the saving throw the OSE SRD gives for it, if any. The adaptations register lists the effects the session leaves to the referee.
  • A petrifying gaze, like the basilisk's or the medusa's, reaches each member in the gazer's group's front rank who stands within 5' of it, once a round. The gaze takes no attack roll. resolve_gaze skips a member who is averting their eyes, is blind, or is incapacitated. A member can avert their eyes, or fight by watching a mirror, through BattleDeclaration.gaze_defense. The session then applies that choice's penalties to the member's attack rolls that round.
  • When a basilisk surprises the party, every member meets its gaze once as the encounter opens, at any distance. The basilisk doesn't gaze again in the monsters' free round that follows.
  • Turned undead attack no one. When a cleric turns only some of a group, the turned monsters split off as a new group and flee. The rest fight on.
  • A member's invisibility ends when the member attacks, throws or uses an item other than a potion, or turns undead. cast_spell ends it when the member casts.
  • Each attack on a target protected by mirror image removes one image instead, and no attack roll is made.
  • A scroll of protection keeps some monsters from attacking the party in melee. Its protection ends when a party member attacks in melee a monster that it keeps out. The session applies it, and protection from evil's melee ban, to every melee a policy chooses, so a policy of your own can't get past either one.
  • A caster maintains one concentration spell at a time. Its effects end when the caster declares anything other than cast or hold, when the caster's next spell is disrupted or fizzles, or when the caster casts another concentration spell. A turn_undead declaration ends them even when the turning doesn't resolve.
  • The session picks the targets of a party member's area spell without a roll. The area fills with the target group's living members in the order they were spawned, as many as the area's size and the rank width allow. Under the Ruleset option aoe_friendly_fire, which is on by default, an area cast at a group also catches the members in that group's front rank who stand within 5' of it, while the area has room. An area aimed at the party, like a dragon's breath, covers the ranks toward the breathing group from the front. A rank at the same distance as the rank in front of it counts as 10' deeper, and a rank farther away starts at its own distance, so the area reaches as many ranks as its size covers.

An action policy chooses what each monster group does each round. ScriptedPolicy is the default for monsters, and NpcPartyPolicy is the default for a party of NPC adventurers. To give a group tactics of your own, write an ActionPolicy and register it in GameSession.action_policies under the group's id. A policy draws only from the MONSTER_ACTION_STREAM, so your policy never changes an attack or damage roll. When the ruleset is set to roll initiative for each combatant, each side still acts together, and the side with the best single roll acts first, because the OSE SRD's combat sequence runs per side.

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.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 (
    BattleDeclaration,
    EngageBattle,
    EnterDungeon,
    ResolveBattleRound,
    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)
members = [
    create_character(
        name=name,
        class_id="fighter",
        alignment=Alignment.LAWFUL,
        ruleset=rules,
        stream=draw,
        purchases=[("sword", 1)],
        equip_ids=["sword"],
    ).character
    for name in ("Hild", "Osric")
]
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=members), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))

# Spawn a group already within reach, then choose to fight it.
session.execute(SpawnMonsters(template_id="goblin", count_fixed=2, distance_feet=5))
session.execute(EngageBattle())
assert session.mode is SessionMode.BATTLE
assert session.battle.round == 0

# One command is one round: a declaration for each member the round expects, from the player view.
encounter = session.view(Visibility.PLAYER).encounter
group_id = encounter.groups[0].id
declarations = tuple(
    BattleDeclaration(character_id=member_id, action="attack", target_group_id=group_id, weapon_id="sword")
    for member_id in encounter.declarers
)
result = session.execute(ResolveBattleRound(declarations=declarations))
assert result.accepted
assert session.battle.round == 1
assert result.events[0].code == "battle.round.started"
assert "combat.initiative.rolled" in [event.code for event in result.events]

FIGHTER_FRONTAGE_FEET module-attribute

FIGHTER_FRONTAGE_FEET = 5

The width, in feet, that one combatant needs to fight side by side with the next.

Each rank of the party is as wide as the space it stands in, divided by this, so two fit abreast in a ten-foot corridor, and a room fits as many as its shorter side allows. The session rejects a melee attack declared by a member within reach of a group but outside its front rank with battle.declaration.not_in_front_rank. The rank check doesn't apply to missile attacks, so the back ranks can still shoot. Each monster group's front rank is as wide, and only the monsters in it make melee attacks, as MonsterAction.kind describes.

The SRD gives one number for this and leaves the rest to the referee: "The referee should judge the number of opponents that can attack a single combatant, bearing in mind the combatant's size and the available space around them. 10' passage: Enough space for at most 2-3 characters to fight side-by-side." osrlib uses the low end of that range, two in ten feet, or five feet each, and applies it to the space the party is standing in.

To play without a width limit, turn off the ruleset's formation_width_limit flag, which puts every living member at the same distance from a group in one rank and every living monster of a group in its front rank. Changing this constant instead would change the width of every space in the game.

FLEE_EXIT_FEET module-attribute

FLEE_EXIT_FEET = 120

How far, in feet, a group that failed its morale check runs before it leaves the battle.

A group that fails a morale check turns and runs its full movement rate each round. Once it stands farther than this from every living party member, as member_distance_feet measures each one, the session marks the group fled. Until then, the party can still close on it or shoot at it. The distance is measured from the members, not from the party line, so a member who closed on the group keeps it in the battle longer, and a move of the party line never pushes a group out.

A fled group takes no further action. The session refuses every declaration aimed at it with battle.declaration.unknown_group. A battle in which every group has fled or died ends in victory.

A group whose living members are all afraid or turned, but which didn't fail a morale check, also counts as gone for ending the battle once it stands farther than this from every living member.

MELEE_RANGE_FEET module-attribute

MELEE_RANGE_FEET = 5

The distance, in feet, at which a party member and a monster group are close enough to fight in melee.

A member who closes on a group stops at this distance from it, not at zero. A group that closes stops at this distance from the nearest member it can see. The session rejects a melee attack declared by a member who would be farther from the group with combat.attack.out_of_reach, and every melee attack resolves at this distance. When pursuing monsters catch the party, the battle starts with every group at this distance and every member on the party line.

The range track has no distance between this and zero, so treat the value as fixed: the session uses it for every reach and range check in a battle. A party member attacks a group farther away only with a missile weapon, and validate_attack checks the distance against that weapon's ranges.

NPC_PARTY_MORALE module-attribute

NPC_PARTY_MORALE = 9

The morale score a group of NPC adventurers checks against, on the usual 2 to 12 scale.

Monsters have a morale score in their stat block, but adventurers in the OSE SRD don't, so osrlib uses the score of the Veteran, the SRD's monster entry for a low-level fighter. This is an adaptation, a place where osrlib commits to one reading of a rule the SRD leaves open. The adaptations register lists each one. With a score of 9, a group passes the check on a 2d6 total of 9 or less, after modifiers, and fails and flees on a higher total.

The battle code reads this value directly, so every NPC adventurer group in the game checks against the same score, and no group can have a different one.

ActionPolicy

Bases: Protocol

The interface for a policy that chooses, each round, what one monster group does.

To give a group tactics of your own, write a class with a choose method that matches this protocol. Register an instance for a group by the group's id in GameSession.action_policies, a dict the session doesn't save. For a group with no entry there, the session uses ScriptedPolicy, or NpcPartyPolicy when its members are NPC adventurers. Policies are code, not saved state, so register yours again after you load a save, as you do listeners.

The session passes your policy the MONSTER_ACTION_STREAM. Take every random choice from that stream. The attack and damage rolls come from other streams, so your policy doesn't change them, and the fight stays reproducible from the same seed. Return whatever actions your tactics call for. The session skips an action it can't carry out, and doesn't raise. The MonsterAction reference lists the cases, field by field.

Whatever your policy returns, only the monsters' front rank makes melee attacks: the group's first living monsters in the group's order, as many as the formation width allows (see MonsterAction.kind). Your policy can't change who stands in front, and the session skips a melee by any other monster. The session also skips every action of a monster that can't act when the action comes up, and a melee on a member whom a ward or protection from evil keeps the monster from. To plan for the front rank, take the group's first living monster_ids, as many as the player view's EncounterView.formation_width.

To keep the default tactics and change one thing, wrap a ScriptedPolicy or a NpcPartyPolicy and change the actions its choose returns.

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.battle import MonsterAction
from osrlib.crawl.commands import (
    BattleDeclaration,
    EngageBattle,
    EnterDungeon,
    ResolveBattleRound,
    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))
session.execute(EngageBattle())

# Monsters that hold their ground and never swing.
class StandStillPolicy:
    def choose(self, session, group, stream):
        return [MonsterAction(monster_id=monster_id, kind="hold") for monster_id in group.monster_ids]

# Register the policy for one group, by group id.
group = session.encounter.groups[0]
session.action_policies[group.id] = StandStillPolicy()

result = session.execute(
    ResolveBattleRound(
        declarations=(BattleDeclaration(character_id=hild.id, action="hold"),),
    )
)
assert result.accepted
assert group.distance_feet == 30  # the goblins never close
assert hild.current_hp == hild.max_hp  # and never swing

choose

choose(session, group, stream) -> list[MonsterAction]

Choose this round's actions for one monster group.

The session calls this once per group per round. For a monster group, the call comes after the group's morale check and before the group moves or attacks. For a group of NPC adventurers, it comes at the start of the round, before initiative, because NPCs declare their spells then, as the party does. The session declares only the casts it can carry out then, and drops the others from the round.

The session doesn't call it in these cases:

  • The group has fled, or has no living members.
  • A monster group is running, because it failed morale or because its living members are all turned or afraid.
  • BattleState.monsters_hold_rounds is above zero. Then the session calls it for no group.

The group you choose for has no living turned members, because the session moves them into a separate group before it calls your policy.

Parameters:

Name Type Description Default
session GameSession

The running session. Read the party, the registry, and the effects ledger from it, and don't change it.

required
group EncounterGroup

The group to choose for. Its distance_feet is its current distance from the party line, and its monster_ids are its members, dead ones included. Call member_distance_feet and group_front_rank to learn which members it can reach.

required
stream RngStream

The MONSTER_ACTION_STREAM stream. Take every random choice from it. A choice from anywhere else makes the fight differ from a replay of the same seed.

required

Returns:

Type Description
list[MonsterAction]

The actions to resolve, in the order they resolve. Return an empty list for a group that does nothing. Leave out members that are dead, incapacitated, or confused, as the built-in policies do. The session skips an action for a member who is dead, can't act, is confused, or is turned. It resolves confusion itself.

BattleRoundPreview

Bases: BaseModel

What a battle round would do with the declarations planned so far, worked out without playing it.

preview_battle_round returns one. Read rejections to grey out a choice the session would refuse, and read advance_feet and front_rank to show where the members would stand once their declared moves are made. The model is frozen.

rejections instance-attribute

rejections: dict[str, tuple[Rejection, ...]]

Every reason the session would refuse each planned declaration, keyed by the declaring member's id. There's one entry for each declaration you passed. An empty tuple means the session would accept that declaration.

The codes and params are the ones ResolveBattleRound returns for the same declarations. battle.declaration.roster_mismatch never appears, because a plan with members still missing would always get it.

advance_feet instance-attribute

advance_feet: dict[str, int]

Where each living member would stand once the planned moves are made, keyed by member id, in feet forward of the party line, as in BattleState.advance_feet. Every living member has an entry. A member with no planned move keeps their current advance, and a member on the line has zero. When the planned moves would leave every member the monsters can see behind the line, the values are the ones after the line moves back, as the round would leave them.

front_rank instance-attribute

front_rank: dict[str, tuple[str, ...]]

For each group that hasn't fled, keyed by group id, the members who would stand in its front rank within 5' of it once the planned moves are made, in marching order. It means what EncounterGroupView.front_rank means, after the moves.

BattleState

Bases: BaseModel

A battle in progress: the round count and what the session tracks from one round to the next.

You get this from session.battle, which is None whenever no battle is running. A battle doesn't replace the encounter. The monster groups, their distances, and their treasure stay on session.encounter, and this model contains only what the fight adds. It's saved with the session, so a saved game resumes in the middle of a battle. Read it to show the battle. The session updates every field as it resolves each round.

To change a fight while it runs, execute a referee command from osrlib.crawl.commands instead of writing to this model. Referee commands are allowed in battle mode, so a referee can grant an item, award experience, set a flag, or advance the clock during a fight. The command log records the command, so a replay reproduces the change. SpawnMonsters adds a new monster group to the fight between rounds, and the group acts from the next round.

SpawnNpcParty and PlaceParty aren't legal in battle, so the session refuses them with session.command.wrong_mode. An NPC party can't join a fight, and you can't move the party out of one.

round class-attribute instance-attribute

round: int = 0

The number of rounds resolved so far. It's 0 between start_battle and the first ResolveBattleRound, unless the monsters had a free round, which counts as round 1.

started_round instance-attribute

started_round: int

The session clock's round count when the battle opened.

monsters_hold_rounds class-attribute instance-attribute

monsters_hold_rounds: int = 0

The rounds in which the monsters still can't act because the party surprised them.

In each round while this is above zero, the monsters do nothing, and the count goes down by one.

morale class-attribute instance-attribute

The MoraleTracker for this battle. It counts each group's passed morale checks, and a group that has passed two doesn't check again.

morale_acted class-attribute instance-attribute

morale_acted: dict[str, list[str]] = {}

The morale triggers each group has already checked for, keyed by group id. A group checks morale once per trigger per battle, so a group that has checked on losing its leader doesn't check again for the same reason.

fired_last_round class-attribute instance-attribute

fired_last_round: list[str] = []

The ids of the party members who, in the last round, fired a weapon that has to be reloaded. validate_attack reads it to apply the reload rule under the ruleset's weapon_reload flag, so the session rejects a second shot in a row.

melee_engagements class-attribute instance-attribute

melee_engagements: dict[str, list[str]] = {}

For each party member id, the monsters that member has attacked in melee. When protection from evil bars a monster from attacking a character, the monster can attack that character anyway once it's on this list, as the spell's text in the SRD says.

concentration class-attribute instance-attribute

concentration: dict[str, list[str]] = {}

For each caster id, the effect ids of the concentration spell that caster maintains. A caster maintains one at a time. The effects end when any of these happens:

  • The caster declares an action other than cast or hold. A turn_undead counts.
  • The caster's next spell is disrupted or fizzles.
  • The caster casts another concentration spell.

advance_feet class-attribute instance-attribute

advance_feet: dict[str, int] = {}

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

The party line is where the party stood when the encounter opened. Each group's distance_feet is measured from it. A member with no entry stands on the line, at zero. A positive advance is toward the monsters, and a negative one is behind the line. A member's distance to a group is the group's distance minus the member's advance, and member_distance_feet works it out for you.

The session changes it in the party's movement step. A member's close raises their advance, and a fighting_withdrawal or a retreat the member makes alone lowers it. A formation move leaves every advance as it is and moves the groups instead.

The party line moves back when the party has fallen back behind it. At the end of the party's movement step, when every living member who isn't invisible stands behind the line, the session moves the line back to the foremost of them. Every member's advance and every group's distance grow by the same number of feet, so no distance between a member and a group changes, and the session emits no event for it. The views show the moved values. The foremost members then stand on the line, at zero, and a group can close on them as usual, because a group's distance never goes below zero. When every living member is invisible, the line stays where it is.

The line also moves back when a group closes on a member who stands behind it and the group's stopping point would be behind the line. That happens when a member the group can see still stands forward of the line, so the movement step left the line where it was. The line moves back by the shortfall in the same way, with no event, and the group then stands on the line.

Every member starts a battle on the line, and the advances end with the battle, so the party stands on its cell as one body again once the fight is over. A save written mid-battle keeps them, and a save from before they existed loads with every member on the line.

arrived_round class-attribute instance-attribute

arrived_round: dict[str, int] = {}

The battle round in which each member reached their current advance, keyed by member id.

A member with no entry has stood where they are since the battle opened, which counts as round zero. The session uses it to order members who stand at the same distance from a group: the member who got there in an earlier round stands in front, and marching order settles a tie. So a member already fighting keeps their place in the front rank when others arrive beside them.

MonsterAction

Bases: BaseModel

One monster's or NPC adventurer's action for a round, as an action policy chooses it.

An ActionPolicy returns a list of these, and the session resolves them in that order. The model is frozen, so to change an action, build a new one with model_copy(update=...). The session doesn't check a policy's actions in advance. When an action comes up, the session skips it if it can't carry it out, and doesn't raise. That covers an action that's no longer possible, like a melee attack on a target that died earlier in the round, and one that never was, like a "breath" by a monster with no breath weapon. The entry for each field below gives the cases where the session skips an action for that field.

monster_id instance-attribute

monster_id: str

The id of the monster or NPC that acts. It has to be one of the monster_ids of the group the policy is choosing for. The session skips an action with any other id, a party member's included, and an action by a monster or NPC that's dead, can't act, is confused, or is turned.

kind instance-attribute

kind: str

What the monster does:

  • "close" moves the whole group up to one encounter movement rate, the acting monster's, toward the nearest living member it can see. The group stops as soon as it's within MELEE_RANGE_FEET of that member, so it never moves past a member it can see, and it reaches that member in as many rounds as its rate needs. An invisible member doesn't stop it, and a member turned to stone does. The move is toward the party line, unless the group passed the member while they were invisible. When the member stands behind the line and the group would stop behind it, the line moves back first, as BattleState.advance_feet describes, so a group's distance never goes below zero. With no member it can see, the group moves toward the line and stops 5' from it. A group already within 5' of a member it can see doesn't move, and the session emits no event for it. Only the first "close" in a group's actions for a round moves the group.
  • "melee" attacks target_id. The session resolves it only if the target stands in the group's front rank within 5' of it when the action comes up, as group_front_rank reports. So a "melee" after the group's "close" strikes when the move has brought the target within reach, and is skipped otherwise. The one exception is a round in which the whole party retreats as a formation. A member who stood in the group's front rank within 5' of it when the round was accepted can then be struck all round, wherever the party has moved, because the OSE SRD gives the opponent its attack against a retreating combatant.

The session also resolves a "melee" only by a monster in the monsters' front rank: the group's first living monsters in the group's order, as many as the formation width (EncounterView.formation_width). A monster keeps its place there while it lives, even when it's asleep or paralysed. So when a policy gives each of six skeletons in a 10' corridor a "melee", the first two skeletons attack and the session skips the other four, in whatever order the policy returned them. With the ruleset's formation_width_limit flag off, every living monster is in the front rank. The session also skips a "melee" on a member whom a scroll of protection's ward or protection from evil keeps the monster from. - "breath" uses the monster's breath weapon on the party. The session skips it for a monster with no breath weapon, for one that has used its breath weapon as many times today as its daily limit allows, and for an NPC adventurer. - "hold" does nothing. - "npc_shoot", "npc_cast", and "npc_drink" are for NPC adventurers only, and the session skips them for a monster. They make a missile attack on target_id, cast spell_id, and drink the potion item_id. The session skips a shot by an NPC who wields no missile weapon.

The session skips an action of any other kind.

target_id class-attribute instance-attribute

target_id: str | None = None

The id of the target, for "melee", "npc_shoot", and an "npc_cast" of a spell with one target. None for an area spell, whose targets depend on the area's size and the party's ranks.

The session skips a "melee" or an "npc_shoot" whose target isn't a living party member, and an "npc_cast" of a spell with one target whose target isn't a living creature. For an area spell, the session ignores the field.

spell_id class-attribute instance-attribute

spell_id: str | None = None

The spell to cast, for "npc_cast". The session skips the cast when the NPC has no memorized copy of the spell, in its normal form, or when the NPC's class casts no spells.

spell_mode class-attribute instance-attribute

spell_mode: str | None = None

Which mode of that spell to use, for "npc_cast". The session skips the cast when the spell's normal form has no mode with this key. The session checks whether the rules allow the cast, like its range, when the cast resolves, and a cast they don't allow does nothing.

item_id class-attribute instance-attribute

item_id: str | None = None

The instance id of the potion to drink, for "npc_drink". The session skips the drink unless the NPC carries a potion with this id.

routine class-attribute instance-attribute

routine: int | None = None

Which of the monster's attack routines a "melee" action uses, as an index into its template's attacks. None uses the first routine.

You can name any routine, whatever its use. The RoutineUse values mean this:

  • PRIMARY is the first routine the monster's entry lists. The session rolls its attacks.
  • ALTERNATIVE is a routine the monster can use in place of the first in any round, like a mule's bite in place of its kick. The session rolls its attacks.
  • SITUATIONAL is a routine for a situation osrlib doesn't model, like an elephant's trample. The session rolls its attacks as melee attacks.
  • SPECIAL is a breath, a gaze, or a spell. The session rolls nothing for it, so the monster does nothing that round.

The session also skips the "melee" when the template has no routine at the index, and it treats a negative index the same way.

Some routines list an attack named gaze or breath. The session never rolls those as attacks. It resolves a petrifying gaze once a round by itself, and a breath weapon through a "breath" action. Your game or the referee handles any other gaze or breath. An NPC adventurer fights with its weapon and ignores this field.

NpcPartyPolicy

The default ActionPolicy for a group of NPC adventurers.

The session uses this policy for a group of NPC adventurers, rather than monsters, unless you register another one for it in session.action_policies. The OSE SRD gives no tactics for a party of adventurers on the other side, so osrlib supplies these. They're one of the entries in the adaptations register.

In the list below, the NPC group is the group this policy chooses for, and the player party is the party your players control. Each living NPC takes the first of these actions that applies:

  1. A caster with a memorized healing spell heals the NPC group's most wounded member who is below half their hit points: the one with the lowest ratio of current to maximum hit points. Of two with the same ratio, it heals the one that comes first in the group's order.
  2. An NPC below half their hit points, in a group with no healing spell left, drinks a healing potion they carry. This is the only item these tactics use.
  3. A caster with a memorized spell that deals damage, like magic missile, casts it at the player party. Spells the referee resolves by hand don't count. The caster picks the highest-level spell, with ties broken by spell id. An area spell catches the player party's ranks toward the NPC group from the front, as many ranks as its size covers. For a spell with one target, the caster picks a member at random from the first row of the player party's ranks toward the NPC group, leaving out invisible members.
  4. An NPC with a missile weapon shoots while every member of the player party it can see is farther than MELEE_RANGE_FEET from the NPC group. It picks its target at random from the first row of the player party's ranks toward the NPC group, leaving out invisible members, and the shot's range band is that member's own distance to the NPC group. So the members in front screen the members behind them from arrows as well as from blades.
  5. Otherwise, the NPC closes, and attacks in melee in the same round when the group's move brings a member within reach. It picks its target at random from the NPC group's front rank, the members group_front_rank lists, leaving out invisible members. Like a monster, it passes over a member turned to stone while a target that isn't stone is in reach. Unlike a ghoul or a thoul, it doesn't pass over a paralysed member.

The NPC group has a front rank as a monster group does: its first living NPCs in the group's order, as many as the formation width allows (see MonsterAction.kind). Only those NPCs make melee attacks, and the party's melee reaches only them. Every NPC can heal, drink, cast, or shoot from wherever it stands, as the party's back ranks can.

NPCs declare their spells at the start of the round. An attack that hits or a failed saving throw can disrupt an NPC's spell, as it can a player character's, because the OSE SRD's rule applies to both sides. NPCs choose all their actions then, so an NPC whom the party puts to sleep, paralyses, or turns to stone before the NPCs act does nothing that round. Every random choice comes from the MONSTER_ACTION_STREAM.

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.battle import NpcPartyPolicy
from osrlib.crawl.commands import (
    BattleDeclaration,
    EngageBattle,
    EnterDungeon,
    ResolveBattleRound,
    SpawnNpcParty,
)
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,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=[hild]), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
session.execute(SpawnNpcParty(party_kind="basic", distance_feet=60))
session.execute(EngageBattle())

# Use the default tactics, and record each round's choices for a referee screen.
class LoggedNpcPolicy:
    def __init__(self) -> None:
        self.default = NpcPartyPolicy()
        self.log: list[list[str]] = []

    def choose(self, session, group, stream):
        actions = self.default.choose(session, group, stream)
        self.log.append([action.kind for action in actions])
        return actions

policy = LoggedNpcPolicy()
session.action_policies[session.encounter.groups[0].id] = policy
session.execute(ResolveBattleRound(declarations=(BattleDeclaration(character_id=hild.id, action="hold"),)))

print(policy.log)  # the fighters close while the rest shoot from 60 feet
# [['close', 'close', 'npc_shoot', 'npc_shoot', 'npc_shoot', 'npc_shoot']]

choose

choose(session, group, stream) -> list[MonsterAction]

Choose this round's actions for one group of NPC adventurers.

The session calls this for you at the start of each round. Call it yourself only from a policy of your own that wraps this one, and pass on the arguments your choose received. A call from anywhere else draws from the session's stream outside any command, so a replay of the command log no longer matches the game.

Parameters:

Name Type Description Default
session GameSession

The running session.

required
group EncounterGroup

The group to choose for.

required
stream RngStream

The MONSTER_ACTION_STREAM stream.

required

Returns:

Type Description
list[MonsterAction]

The MonsterActions for each living member that can act, in the group's member order: one action, or a close followed by a melee when the group's move will bring a member within reach. Incapacitated and confused members get none.

ScriptedPolicy

The default ActionPolicy for monsters: breathe, or close and attack.

The session uses this policy for every monster group unless you register another one for it in GameSession.action_policies. You construct one yourself only to wrap it in a policy of your own. Its choose(session, group, stream) method is the ActionPolicy method. It takes the running session, the monster group to choose for, and the stream of random numbers the session passes in, and it returns a list of MonsterActions.

A monster with a breath weapon uses it while the nearest member the group can see is within the breath's length:

  • When the breath weapon has a number of uses per day, the monster breathes if it hasn't breathed yet that day. After that, it breathes or attacks with equal chance while uses remain, which is how the OSE SRD's dragons fight.
  • When the breath weapon works on a chance in six, as the hellhound's does, the policy rolls that chance each round.

Otherwise, while every member the group can see is farther than MELEE_RANGE_FEET from it, each monster takes a close action. When the group's move will bring a member within reach, each monster also takes a melee action in the same round, aimed at a member of the front rank the move will produce. Once the group is within reach, each monster picks a target at random from the group's front rank, the members group_front_rank lists. It leaves out invisible members, and members whose protection from evil bars that monster. When no target is left, the monster takes a hold action and does nothing that round. The members behind the front rank are out of the group's reach. Every monster with a target gets a melee action, but the session resolves only those of the monsters' front rank, the group's first living monsters, as many as the formation width allows (see MonsterAction.kind). The rest make no attack that round.

Among the targets left, the monster prefers members who can still fight:

  • It passes over a member turned to stone while a target that isn't stone is in reach, because a statue is out of the fight. When every target in reach is stone, it attacks a statue.
  • A monster whose paralysis ability has the param attacks_others, like the ghoul and the thoul, also passes over a paralysed member while a target that is neither paralysed nor stone is in reach. That's the OSE SRD's "After paralysing a target, ghouls will attack others". The monster still picks a paralysed member before a statue.

The policy picks a target once a round, so a paralysing hit doesn't move the rest of that round's attacks to another target.

The monster then picks which of its attack routines to use. It chooses with equal chance among the routines whose use is PRIMARY or ALTERNATIVE, and puts the choice in MonsterAction.routine. For example, a thoul claws or swings a weapon, and a mule kicks or bites. The policy never picks a SITUATIONAL or SPECIAL routine, like an elephant's trample or a vampire's gaze. For a monster with only one routine to pick from, the policy makes no random roll.

The monster data has no ranges for monsters' missile attacks, so osrlib treats them like melee: the monster closes first, then attacks. This is one of the entries in the adaptations register. Monsters under this policy never cast spells, because the monster data doesn't cover monster spellcasting, which is the referee's call.

Write a policy of your own when you want a group to stand in a doorway and block it, aim every attack at one member, back off, cast, or use a situational routine when your game decides the situation calls for it. To keep these tactics and change one thing, wrap this policy and change the actions its choose returns, as the example does. NpcPartyPolicy is the built-in policy for NPC adventurers, which also heals, drinks potions, casts, and shoots.

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.battle import ScriptedPolicy
from osrlib.crawl.commands import (
    BattleDeclaration,
    EngageBattle,
    EnterDungeon,
    ResolveBattleRound,
    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)
members = [
    create_character(
        name=name,
        class_id="fighter",
        alignment=Alignment.LAWFUL,
        ruleset=rules,
        stream=draw,
    ).character
    for name in ("Hild", "Osric")
]
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,))
adventure = Adventure(name="A First Delve", town=TownSpec(name="Threshold"), dungeons=(crypt,))
session = GameSession.new(Party(members=members), adventure, seed=7)
session.execute(EnterDungeon(dungeon_id="crypt"))
session.execute(SpawnMonsters(template_id="goblin", count_fixed=3, distance_feet=5))
session.execute(EngageBattle())

# Keep the default tactics, but aim every melee attack at the most wounded of the members picked.
class FocusFirePolicy:
    def __init__(self) -> None:
        self.default = ScriptedPolicy()
        self.last = []

    def choose(self, session, group, stream):
        actions = self.default.choose(session, group, stream)
        targets = [session.member(action.target_id) for action in actions if action.kind == "melee"]
        if targets:
            weakest = min(targets, key=lambda member: member.current_hp)
            actions = [
                action.model_copy(update={"target_id": weakest.id}) if action.kind == "melee" else action
                for action in actions
            ]
        self.last = actions
        return actions

policy = FocusFirePolicy()
session.action_policies[session.encounter.groups[0].id] = policy
hold = tuple(BattleDeclaration(character_id=member.id, action="hold") for member in members)
session.execute(ResolveBattleRound(declarations=hold))

print([(action.kind, action.target_id) for action in policy.last])
# [('melee', 'character-0001'), ('melee', 'character-0001'), ('melee', 'character-0001')]

choose

choose(session, group, stream) -> list[MonsterAction]

Choose this round's actions for one monster group.

The session calls this for you. Call it yourself only from a policy of your own that wraps this one, and pass on the arguments your choose received. A call from anywhere else draws from the session's stream outside any command, so a replay of the command log no longer matches the game.

Parameters:

Name Type Description Default
session GameSession

The running session.

required
group EncounterGroup

The group to choose for.

required
stream RngStream

The MONSTER_ACTION_STREAM stream.

required

Returns:

Type Description
list[MonsterAction]

The MonsterActions for each living monster that can act, in the group's member order: one action, or a close followed by a melee when the group's move will bring a member within reach. Incapacitated and confused monsters get none, because the session resolves confusion itself.

group_front_rank

group_front_rank(session, group_id: str) -> tuple[str, ...]

Return the members who can fight one monster group hand to hand this round without moving.

These are the members in the party's front rank toward the group who stand within MELEE_RANGE_FEET of it. Only they can declare a melee attack on the group, or strike it for a charge with a staff of power, striking, or wizardry, without a close first. Only they can be struck by the group's melee, and the group's petrifying gaze reaches only them. Only the monsters' front rank strikes them: the group's first living monsters, as many as the formation width allows.

The ranks toward a group are the party's living members sorted by their distance to it, nearest first, and cut into rows as wide as the formation allows (EncounterView.formation_width). A row never mixes distances. Among members at the same distance, the one who got there in an earlier round (BattleState.arrived_round) stands in front, and marching order settles a tie. The front rank is the first row. With the ruleset's formation_width_limit flag off, a row holds every member at its distance.

So two orders apply, one after the other. Arrival order, then marching order, decides who is in the front row. The returned tuple then lists the members of that row in marching order. A member who got there first can come after a member who arrived later, and a member who marches ahead of both can be left out because the row was already full.

For the same group, the result is always the same value as EncounterGroupView.front_rank in the player view.

Call it from a policy of your own: the default policies pick each monster's melee target from these members, leaving out invisible members and members whose protection from evil bars that monster. A client that has only the player view reads the same ids from EncounterGroupView.front_rank.

The call reads the session and changes nothing.

Parameters:

Name Type Description Default
session GameSession

A session in battle mode.

required
group_id str

The group's id, as in EncounterGroupView.id.

required

Returns:

Type Description
tuple[str, ...]

Member ids, in marching order. It's empty when no living member stands within 5' of the group, for example while the nearest row is still farther away.

Raises:

Type Description
ValueError

If no battle is running, or group_id names no group in the encounter. Nothing in the session changes.

member_distance_feet

member_distance_feet(session, member_id: str, group_id: str) -> int

Return how far one party member stands from one monster group, in feet, in the running battle.

Each group's distance is measured 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 an advance forward of that line, in BattleState.advance_feet. This returns the group's distance minus the member's advance. Every rule that measures how far a member is from a group uses it: melee reach, a missile's range band, and a spell's range.

The value is negative only for a member the group has passed, which a group does only to a member it can't see. The rules measure such a member by the size of the value, so a member at -5 is within reach of the group.

Call it from a policy of your own (see ActionPolicy) or from server-side code that has the session. A client that has only the player view reads the same numbers from EncounterGroupView.member_distance_feet.

The call reads the session and changes nothing.

Parameters:

Name Type Description Default
session GameSession

A session in battle mode.

required
member_id str

The member's id, as in MemberView.id.

required
group_id str

The group's id, as in EncounterGroupView.id.

required

Returns:

Type Description
int

The distance in feet. At MELEE_RANGE_FEET or less, the member and the group are within reach of each other.

Raises:

Type Description
ValueError

If no battle is running, member_id names no party member, or group_id names no group in the encounter. Nothing in the session changes.

preview_battle_round

preview_battle_round(session, declarations: Sequence[BattleDeclaration]) -> BattleRoundPreview

Judge the declarations planned so far for this battle round, and show where they'd leave the party.

A battle screen builds a round one member at a time. Call this after each choice, with every declaration made so far, to learn whether the session would accept each one and where each member would stand. For example, once Hild has planned to close and attack, and her place fills the front rank toward the goblins, the preview refuses Osric's close and attack with battle.declaration.not_in_front_rank. Your screen can then offer Osric a close without the attack. When the plan is complete, send it in a ResolveBattleRound.

A declaration that acts on another member is judged where the two would stand too. That's a potion given to another member to drink, a give_item, a staff of healing's touch, and a spell cast at a member. So once Hild has planned to close 20' toward the goblins, the preview refuses a potion the cleric beside her planned to give her with battle.declaration.member_out_of_reach, and a cure light wounds on her with magic.cast.out_of_range.

The preview runs the checks ResolveBattleRound runs before it plays a round, over the same projection of the round's declared moves, so the two agree. When declarations has one declaration for each member in EncounterView.declarers and every entry in the result's rejections is empty, ResolveBattleRound accepts the same declarations.

The projection applies each planned move as the party's movement step would: each member's close, and each fighting_withdrawal or retreat a member makes alone. A partial plan, one that leaves out some declarers, judges each fighting_withdrawal or retreat as that member's own move, even when every member in the plan makes the same one. The complete plan can turn into a formation move: when every declarer makes the same defensive move, the whole party moves back as one body, the groups move back instead of the members, and the preview of the complete plan shows that. So a member's projected advance can change when the last declaration is added. The order of declarations doesn't matter. The projection doesn't include anything the monsters do, because the session decides that after it rolls initiative. So when the monsters act first, a member's close can fall short of where the preview put them.

The call reads the session and changes nothing. It takes no random number and no game time, so calling it after every choice costs the game nothing.

Parameters:

Name Type Description Default
session GameSession

A session in battle mode.

required
declarations Sequence[BattleDeclaration]

The declarations planned so far, at most one for each member. Each one names a member in EncounterView.declarers. Any subset of the declarers works, including none.

required

Returns:

Type Description
BattleRoundPreview

A BattleRoundPreview with each declaration's rejections, each living member's projected advance, and each group's projected front rank.

Raises:

Type Description
ValueError

If no battle is running, a declaration names a member who isn't in EncounterView.declarers, or two declarations name the same member. Fix the call. Nothing in the session changes.

start_battle

start_battle(session, *, party_free_round: bool = False, monsters_free_round: bool = False) -> list[Event]

Start a battle on the session's open encounter and put the session in battle mode.

Don't call this in normal play. Execute EngageBattle instead, and the session calls this for you. It also calls this when the monsters attack and when pursuing monsters catch the party. The command works out which side surprised the other, and the command log records it, so a replay of the log reproduces the fight. A direct call changes the session outside any command, so a replay doesn't reproduce it. Call this only from code that runs outside the session's commands, like a test of combat.

The session needs an open encounter, because the battle uses that encounter's groups and their distances, and it must not have a battle open already. When this function returns, the session is in battle mode and session.battle contains a BattleState. From there, each round is one ResolveBattleRound command.

A group with a morale score of 2 never fights, so it flees as soon as the battle starts. That can end the battle before any round. When a cleric turned only part of a group, the turned monsters split off as a new group, which flees from the first round.

A side that surprised the other gets one free round, in which the other side doesn't act:

  • The monsters' free round runs inside this call, before the party can act.
  • On the party's free round, the monsters don't act in the first round, which you resolve with the first ResolveBattleRound. BattleState.monsters_hold_rounds counts the rounds in which the monsters still don't act.

Parameters:

Name Type Description Default
session GameSession

The running session, with session.encounter set.

required
party_free_round bool

True when the monsters were surprised. The monsters then don't act in the first round.

False
monsters_free_round bool

True when the party was surprised. The monsters then act once inside this call, before the party declares anything.

False

Returns:

Type Description
list[Event]

The opening events: the BattleStartedEvent, a MonsterFledEvent for each group that ran at once, the events of the monsters' free round, including the clock advancing one round, and a BattleEndedEvent when the opening alone ends the battle.

Raises:

Type Description
ValueError

If no encounter is open on the session, or if a battle is already open on it. 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.battle import start_battle
from osrlib.crawl.commands import 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))

# The goblins were surprised, so the party gets the first round free.
events = start_battle(session, party_free_round=True)
assert [event.code for event in events] == ["battle.started"]
assert session.mode is SessionMode.BATTLE
assert session.battle.round == 0
assert session.battle.monsters_hold_rounds == 1