Skip to content

osrlib.core.combat

Resolve B/X combat: initiative, attacks, damage, saving throws, morale, and targeting.

Every function here works on the creatures and dice streams you pass in, changes the creatures in place where the rules say so, and reports what happened as events. A script with no session, dungeon, or battle can roll a whole fight with them, as the guide Using the rules without a session shows. A session is a GameSession, which runs a whole game. Inside one, osrlib.crawl.battle calls these same functions in the B/X round sequence, so a session logs the same events these functions return.

In the order you use them in a combat round:

Some attacks resolve through a separate function instead of resolve_attack: resolve_splash_attack for thrown holy water and oil, resolve_breath for breath weapons, resolve_gaze for petrifying gazes, and resolve_energy_drain for the level drain that follows an undead creature's hit. select_targets chooses which of the candidates you list a spell reaches. Outside a fight, roll_reaction rolls how monsters react to the party, apply_healing and natural_healing restore hit points, and falling_damage rolls the damage of a fall. The rest of the module is the steps resolve_attack runs, which you can call one at a time.

Each parameter that takes a creature, like attacker, defender, or target, is typed with a protocol from osrlib.core.creature. A Character and a MonsterInstance both satisfy each protocol. A function that reads THAC0, armour class, or saving throws takes a Combatant. A function that reads only hit points, conditions, and stat modifiers takes a Creature. Every Combatant is also a Creature, so you can pass the same character or monster to both kinds of function. A function that needs what only a monster has, like the daily breath count, takes a MonsterInstance. An NPC adventurer is a Character.

Attack functions also take an AttackContext, which states the situation of the attack, like the distance, cover, or a back-stab position. Most functions take the Ruleset in play, and every function that rolls dice takes an RngStream, a named source of random numbers. The RNG streams reference lists the streams. There's no default stream. Build an RngStreams from a master seed and pass each function the stream it draws from. Battle draws come from COMBAT_STREAM. roll_reaction draws from the encounter stream, natural_healing from the effects stream, and drain_monster_hd and resolve_energy_drain from the advancement stream.

Each function that resolves part of a fight returns events, either as a list or in the events tuple of a frozen result model. Append them to your log. The result models also have the outcome as plain fields, like hit and damage, in case you don't keep a log. damage_roll and falling_damage only roll dice, and return a RollResult with no events.

Damage from an attack goes through these steps in this order:

  1. The immunity check: whether the defender's defenses let the attack harm it at all. If they don't, osrlib rolls no damage, and a DamageAbsorbedEvent reports the hit.
  2. The damage roll: the dice, the attacker's STR modifier in melee, magic and spell bonuses, then the doublings for a brace, a charge, or a back-stab. The total is at least 1.
  3. The defender's reductions, like the wraith's half damage from silver or resist fire's 1 point off each die. None of them takes the damage below 1.
  4. The hit points come off, stopping at 0. Fire and acid also count against a troll's regeneration. A defender at 0 hit points dies.

A monster attack that deals no hit point damage, like a wight's touch, stops after the immunity check.

validate_attack and validate_breath check an action before you resolve it. They make no random roll, change nothing, and return a list of Rejection values, which is empty when the action may go ahead. A session refuses a rejected command without spending a roll or any game time. That's why holy water thrown at a living creature isn't rejected: it hits and does nothing. Rejecting it would tell the player, at no cost, which creatures are undead.

Typical usage:

from osrlib.core.combat import COMBAT_STREAM, AttackContext, Participant, check_morale, resolve_attack, roll_initiative
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

rules = Ruleset()
streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
orc = spawn_monster(catalog.get("orc"), id="orc-1", stream=spawn)

combat = streams.get(COMBAT_STREAM)
initiative = roll_initiative(
    [Participant(key="goblin-1", side="goblins"), Participant(key="orc-1", side="orcs")],
    ruleset=rules,
    stream=combat,
)
assert initiative.order == ("goblin-1", "orc-1")

sword = load_equipment().get("sword")
attack = resolve_attack(goblin, orc, sword, context=AttackContext(), ruleset=rules, stream=combat)
assert attack.attack_roll.hit
assert attack.damage == 4
assert orc.current_hp == 3  # down from 7

morale = check_morale("orcs", orc.template.morale, stream=combat)
assert not morale.held  # 2d6 showed 9 against the orc's morale score of 6

Attack module-attribute

What a combatant attacks with. None is an unarmed attack, which deals 1d2.

resolve_attack, attack_roll, damage_roll, validate_attack, and damage_source_for take one. Each form comes from a different place:

  • A WeaponTemplate or a GearTemplate comes from load_equipment. The equipment id index lists the ids.
  • A CombatFacet is the combat field of a gear template: the item's damage dice, qualities, and ranges without the item. An attack with a bare facet is named improvised in its event. Pass the gear template itself for holy water, a torch, or oil, because the facet has no item id to tell them apart.
  • A MonsterAttack comes from the attacking monster's template.
  • A MagicItemInstance comes from a character's inventory or from treasure generation.

A MagicItemInstance attack is a magic weapon. Its base weapon gives the dice, qualities, and ranges, and its template gives the attack and damage bonus. A magic weapon with a bonus against certain monsters, like a Sword +1, +3 vs Dragons, uses the higher bonus when the defender's template is one of them. Every magic weapon counts as magical against a defender that only magic can harm, and a cursed one does too.

Use attack_facet to get the dice, qualities, and ranges behind any of these forms without checking which form you have.

Examples:

from osrlib.core.combat import attack_facet
from osrlib.data import load_equipment, load_monsters

sword = load_equipment().get("sword")
assert attack_facet(sword).damage == "1d8"

goblin_attack = load_monsters().get("goblin").attacks[0].attacks[0]
assert goblin_attack.damage == "1d6"
assert attack_facet(None) is None  # unarmed has no facet

COMBAT_STREAM module-attribute

COMBAT_STREAM = StreamName.COMBAT

The stream key for battle draws: attacks, damage, saving throws, morale, and initiative.

Pass it to RngStreams.get to get the stream that most functions in this module draw from. Reaction rolls, natural healing, and energy drain draw from other streams, which their functions' descriptions give. A GameSession draws its battle rolls from this key too.

A stream key is a name. The same master seed and the same key always produce the same sequence of draws, so a script that seeds its streams the same way rolls the same fight every time. Any key works for a script of your own, but with this one your battle draws come from the same stream a session uses for battles.

Examples:

from osrlib.core.combat import COMBAT_STREAM
from osrlib.core.rng import RngStreams

combat = RngStreams(master_seed=3).get(COMBAT_STREAM)
assert combat.randbelow(20) + 1 == 20

MELEE_REACH_FEET module-attribute

MELEE_REACH_FEET = 5

How far a melee attack reaches, in feet.

When an AttackContext states a distance_feet greater than this, validate_attack rejects a melee-only attack, and a weapon that's both melee and missile is thrown or fired instead of swung.

AttackContext

Bases: BaseModel

The situation an attack happens in, as you state it.

Build one and pass it as the context of resolve_attack and the other functions that take one. An empty AttackContext() is the plain case: a melee swing at a defender that's aware of the attack and not retreating. The model is frozen, so build a new one for each attack instead of changing one.

Most of these fields are judgments the tabletop rules leave to the referee, like whether the target is unaware of the attacker. The combat functions apply the rules to the context you give them and don't work any of it out themselves. A GameSession fills it in from the state of its battle, so you don't build one when a session runs the fight.

Examples:

from osrlib.core.combat import AttackContext

plain = AttackContext()
assert plain.distance_feet is None
assert plain.situational_modifier == 0

back_stab = AttackContext(behind_target=True, target_unaware=True)
assert back_stab.behind_target and back_stab.target_unaware

distance_feet class-attribute instance-attribute

distance_feet: int | None = None

How far apart the attacker and the defender are, in feet, or None to leave it unstated.

With no distance, a melee weapon and a weapon that's both melee and missile are swung in melee, and a missile-only weapon is fired with no range modifier. A distance over MELEE_REACH_FEET makes a melee-and-missile weapon a missile, and makes validate_attack reject a melee-only attack. A missile's distance sets its range modifier: +1 at short range, 0 at medium, and −1 at long.

situational_modifier class-attribute instance-attribute

situational_modifier: int = 0

The referee's adjustment to the attack roll, like −1 to −4 for cover, or +2 against a sleeping dragon.

defender_ally_ac_bonus class-attribute instance-attribute

defender_ally_ac_bonus: int = 0

How much an ally's magic improves the defender's armour class.

A Ring of Protection 5' Radius protects the creatures near its wearer, for example. Which creatures are near enough is your judgment, so you pass the bonus here. A positive value makes the defender harder to hit.

behind_target class-attribute instance-attribute

behind_target: bool = False

Whether the attacker strikes from behind.

The defender's shield doesn't count, as the OSE SRD's "AC bonuses from shields are negated" says. The attack is made against the armour class the defender would have without the shield, so a magic shield loses its enchantment along with the +1 that every shield gives. A cursed shield that makes the defender's armour class worse still counts, because the rule takes away a shield's bonus and not its penalty. With target_unaware, a thief attacker gets the back-stab bonus to hit and to damage, and the attack's AttackRolledEvent has back_stab set.

target_unaware class-attribute instance-attribute

target_unaware: bool = False

Whether the defender is unaware of the attack.

With behind_target, a thief attacker gets the back-stab bonus to hit and to damage, and the attack's AttackRolledEvent has back_stab set.

defender_retreating class-attribute instance-attribute

defender_retreating: bool = False

Whether the defender is retreating.

The attacker gets +2 to hit, and the defender's shield doesn't count, as it doesn't with behind_target. The attack is made against the armour class the defender would have without the shield, a magic shield's enchantment included, but never a better one. A GameSession sets it for you in two cases:

  • On an attack against a monster group that's fleeing.
  • On every attack from the monster side against a party member who declared a retreat that round. When the whole party retreats, that's every member. The retreat counts from the start of the round, so it applies to monsters that act before the member moves.

braced class-attribute instance-attribute

braced: bool = False

Whether the attacker has set a brace-quality weapon, like a spear, against a charge. Its damage doubles.

charging class-attribute instance-attribute

charging: bool = False

Whether the attacker is charging with a charge-quality weapon, like a lance. Its damage doubles.

fired_last_round class-attribute instance-attribute

fired_last_round: bool = False

Whether the weapon was fired in the previous round.

Under the weapon_reload ruleset flag, validate_attack then rejects a reload-quality weapon, like a crossbow.

attacker_large class-attribute instance-attribute

attacker_large: bool = False

Whether the attacker is a large creature.

A halfling defender then gets its armour class bonus against large opponents.

lit class-attribute instance-attribute

lit: bool = False

Whether a thrown oil flask is alight. Unlit oil deals no damage and no fire.

fixed_damage_option class-attribute instance-attribute

fixed_damage_option: int = 0

Which of a monster attack's fixed_damage_options to use, counting from 0.

It matters only for a monster attack that lists more than one fixed amount, like an insect swarm's 2 or 4.

monster_missile class-attribute instance-attribute

monster_missile: bool = False

Whether the monster's attack is a small missile, like a hobgoblin's arrow.

When it's true, protection from normal missiles blocks the attack. The attack also doesn't hit a paralysed, sleeping, or petrified defender automatically, as a melee attack does. osrlib never sets this for you, because some monster missiles, like a hurled boulder, aren't small.

AttackResult

Bases: BaseModel

The outcome of one whole attack: the roll, whether the defender's defenses stopped it, and the damage.

resolve_attack and resolve_splash_attack return one. By the time you have it, the damage is already applied to the defender, so the result reports what happened and leaves nothing for you to apply. The model is frozen.

attack_roll instance-attribute

attack_roll: AttackRollResult

The attack roll.

absorbed class-attribute instance-attribute

absorbed: bool = False

Whether the attack hit and the defender's defenses stopped all its damage, so none was rolled.

A miss is never absorbed.

damage class-attribute instance-attribute

damage: int | None = None

The damage rolled, before the defender's reductions, or None when none was rolled.

osrlib rolls no damage on a miss, on an absorbed hit, or when a blade kills a sleeping defender outright. It's 0 for an unlit oil flask that hits, and for a monster attack that deals no hit point damage, like a wight's touch.

The defender can lose fewer hit points than this. The DamageDealtEvent in events has the amount after reductions, and the HitPointsReportedEvent after it has the hit points the defender has left.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

Every event the attack produced, in order, ready to append to your log.

AttackRollResult

Bases: BaseModel

An attack roll's outcome: whether it hit, and the numbers behind it.

attack_roll returns one, and an AttackResult has one in its attack_roll field. Read hit to decide what happens next, and the other fields to show the player the arithmetic. The model is frozen.

hit instance-attribute

hit: bool

Whether the attack hit.

auto class-attribute instance-attribute

auto: bool = False

Whether the attack hit without a roll.

That happens in melee against a defender that's paralysed, asleep, or petrified. It also happens against a monster whose template has no armour class, like green slime and yellow mould, because attacks against it need no roll. When this is true, roll, total, and required are None, and the function made no random roll.

roll class-attribute instance-attribute

roll: int | None = None

The d20 as it landed, before modifiers, or None on an automatic hit.

modifier class-attribute instance-attribute

modifier: int = 0

The sum of every modifier added to the roll. It can be negative.

total class-attribute instance-attribute

total: int | None = None

roll plus modifier, or None on an automatic hit.

required class-attribute instance-attribute

required: int | None = None

The total the attack needed to hit, or None on an automatic hit.

It comes from the B/X attack table for the attacker's THAC0 and the defender's armour class, or from THAC0 − AC under the thac0_arithmetic ruleset flag.

natural class-attribute instance-attribute

natural: int | None = None

1 or 20 when the d20 alone decided the outcome, and None otherwise.

A natural 20 always hits and a natural 1 always misses. This field is set only when that rule changed the outcome: a 20 whose total was below required, or a 1 whose total reached it. Use it to tell a lucky hit from an ordinary one.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

The roll's AttackRolledEvent, ready to append to your log.

DamageSource

Bases: BaseModel

The properties of one source of damage that the defender's defenses are checked against.

osrlib checks it against the defender's defenses to decide whether the damage harms the defender, and how much. Build one with damage_source_for from an attacker, an attack, and a context. For damage that isn't an attack, like a spell, a trap, or a fall, construct one yourself. Pass it to check_immunity to ask whether the defender is immune to it, and to deal_damage to apply the damage. The model is frozen.

Examples:

from osrlib.core.combat import DamageSource

dragon_breath = DamageSource(element="fire", kind="breath", destructive=True)
assert dragon_breath.keys == ()
assert not dragon_breath.magical

silver_dagger = DamageSource(keys=("silver",))
assert silver_dagger.kind == "weapon"  # the default delivery

keys class-attribute instance-attribute

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

The material and enchantment keys of the source, like silver, magic, or holy.

A monster that only some materials can harm lists them in its harmed_only_by defense. A source harms that monster only when it has one of the listed keys, so a magic weapon has magic and a silver one has silver. Damage reductions can also depend on the keys, like the wraith's half damage from silver.

element class-attribute instance-attribute

element: str | None = None

The energy element, like fire, cold, or lightning, or None for physical damage.

The values are those of Element. Energy defenses, spells like resist fire, and a troll's regeneration all depend on the element.

magical class-attribute instance-attribute

magical: bool = False

Whether the source is magical.

A monster that's immune only to the ordinary form of an element, as a red dragon is to fire, takes damage from a magical source of that element and none from a nonmagical one. Protection from normal missiles blocks only a nonmagical missile. osrlib checks a harmed_only_by defense against keys instead, so a magic source also has the magic key.

kind class-attribute instance-attribute

kind: str = 'weapon'

How the damage is delivered, like weapon, breath, or falling.

The model accepts any string. damage_source_for sets weapon, unarmed, monster, or splash, and the rest of osrlib uses breath, spell, device, effect, trap, falling, and deprivation. osrlib reads it in two places. When a destructive source kills a creature, its magic items save versus breath for breath, versus spells for spell, versus wands for device, and versus death for any other kind. A monster that uses fire is immune to a nonmagical fire source of kind splash, which is burning oil.

destructive class-attribute instance-attribute

destructive: bool = False

Whether the source destroys what the victim carries when it kills the victim.

Breath weapons and lightning bolt do. destroy_equipment describes what's destroyed and which magic items get a save.

missile class-attribute instance-attribute

missile: bool = False

Whether the source is a small missile, which protection from normal missiles blocks.

damage_source_for sets it for a character's missile weapon and a thrown splash item. It sets it for a monster attack only when the context's monster_missile is true, because some monster missiles, like a hurled boulder, aren't small.

InitiativeResult

Bases: BaseModel

The outcome of an initiative roll: every roll, re-rolls included, and the acting order.

roll_initiative returns one. Go through order to run the round. The model is frozen.

mode instance-attribute

mode: str

side when each side rolled once, or individual when each participant rolled.

The individual_initiative ruleset flag selects which.

entries instance-attribute

entries: tuple[InitiativeRoll, ...]

One InitiativeRoll for each key that rolled.

A key is a side under side initiative, and a participant under individual initiative. The entries are in the order the keys first appear in the list you passed. Each entry's rolls has every die rolled for it, so a tie that was re-rolled shows each roll.

order instance-attribute

order: tuple[str, ...]

Every participant's key, in the order they act. Slow participants come last.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

The roll's InitiativeRolledEvent, ready to append to your log.

MoraleResult

Bases: BaseModel

A morale check's outcome: whether the side keeps fighting.

check_morale and MoraleTracker.check return one. When held is false, the side flees or surrenders, and making it do so is up to you. The model is frozen.

held instance-attribute

held: bool

Whether the side keeps fighting.

It's false for a side with a morale score of 2 or less, which never fights, even though no roll was made.

exempt class-attribute instance-attribute

exempt: bool = False

Whether the side's morale score means it doesn't roll.

A side with a score of 2 or less never fights, and a side with 12 or more never checks. When this is true, roll is None and no draw was taken.

roll class-attribute instance-attribute

roll: int | None = None

The 2d6 total, before the modifier, or None when the side was exempt.

modifier class-attribute instance-attribute

modifier: int = 0

The adjustment that was applied, after it was limited to the range −2 to +2.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

The check's MoraleCheckedEvent, ready to append to your log.

It's visible to the referee only, because players learn a side's morale from what it does.

MoraleTracker

Bases: BaseModel

Counts morale checks through one encounter, so a side that holds twice stops checking.

Build one for each encounter and check morale through it instead of calling check_morale directly. It applies the rule "If a monster passes two morale checks in an encounter, it will fight until killed, with no further checks."

A tracker can be changed, unlike the result models in this module, because it keeps a count through the encounter. Build a new one for the next encounter, which starts the count again. A session's battle keeps one for you.

passed class-attribute instance-attribute

passed: dict[str, int] = {}

How many checks each side has held, by the side's key as you pass it to check.

The tracker never checks a side at 2 again.

check

check(subject: str, score: int, *, modifier: int = 0, stream: RngStream) -> MoraleResult | None

Check a side's morale, unless it has already held twice in this encounter.

check_morale makes the check, and this method counts it. An exempt side, at morale 2 or less or 12 or more, never adds to the count, because it never rolls.

Parameters:

Name Type Description Default
subject str

The side's key. The tracker counts each key apart, so two groups of goblins with different keys are counted apart.

required
score int

The morale score, which is 2 to 12 on a stat block. The method accepts any integer. A score of 2 or less, or of 12 or more, is exempt, as in check_morale.

required
modifier int

The adjustment to the roll. A value outside −2 to +2 counts as −2 or +2.

0
stream RngStream

The stream the 2d6 comes from, usually COMBAT_STREAM. The method takes no draw once the side has held twice.

required

Returns:

Type Description
MoraleResult | None

The check's outcome, or None when the side has held twice and fights until it's killed, with no check made.

Examples:

from osrlib.core.combat import COMBAT_STREAM, MoraleTracker
from osrlib.core.rng import RngStreams

combat = RngStreams(master_seed=3).get(COMBAT_STREAM)
tracker = MoraleTracker()

first = tracker.check("goblins", 10, stream=combat)
second = tracker.check("goblins", 10, stream=combat)
assert first.held and second.held
assert tracker.passed == {"goblins": 2}

assert tracker.check("goblins", 10, stream=combat) is None  # they fight on

Participant

Bases: BaseModel

One combatant in an initiative roll: its key, its side, and what changes its place in the order.

Build one for each combatant and pass the list to roll_initiative. List them in the order you want combatants with the same rank to act in. The model is frozen.

key instance-attribute

key: str

The combatant's identifier, which comes back in the acting order.

Use the entity id you already track, so you can match the order to your creatures. Each participant needs a different key.

side instance-attribute

side: str

The name of the side the combatant fights on, like party or goblins.

Under side initiative, everyone on a side acts on that side's single roll.

slow class-attribute instance-attribute

slow: bool = False

Whether the combatant fights with a slow weapon, like a two-handed sword.

A slow combatant acts after every combatant that isn't slow, whatever the rolls are.

modifier class-attribute instance-attribute

modifier: int = 0

The combatant's modifier to an individual initiative roll.

It's used only when the individual_initiative ruleset flag is on. Get it from participant_modifier, which gives a character its DEX modifier plus the halfling's class bonus, and a monster the modifier you choose.

ReactionRollResult

Bases: BaseModel

A reaction roll's outcome: the 2d6, the modifier, and how the monsters react.

roll_reaction returns one. What the monsters do about it is up to you. The model is frozen.

result instance-attribute

How the monsters react: attacks, hostile, uncertain, indifferent, or friendly.

roll instance-attribute

roll: int

The 2d6 total, before the modifier.

modifier class-attribute instance-attribute

modifier: int = 0

The modifier you passed.

total instance-attribute

total: int

roll plus modifier.

It can fall outside 2 to 12. roll_reaction reads a total below 2 as 2, and a total above 12 as 12.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

The roll's ReactionRolledEvent, ready to append to your log.

It's visible to the referee only, because players learn a monster's mood from what it does.

SaveCategory

Bases: StrEnum

The B/X saving throw categories.

Pass one to saving_throw. The category depends on what forces the save: each spell lists its category, and a breath weapon uses breath. When a destructive source kills a creature, its magic items save in the category that matches the source.

Each value is the lowercase name of a field of SavingThrows, which has a creature's target number for that category. The values appear in events and saved games, and stay fixed within a schema_version, the version stamp of the saved format.

DEATH class-attribute instance-attribute

DEATH = 'death'

Death ray or poison. It's also the category for anything that has no other category.

WANDS class-attribute instance-attribute

WANDS = 'wands'

Magic wands, and other magic devices.

PARALYSIS class-attribute instance-attribute

PARALYSIS = 'paralysis'

Paralysis or turning to stone, which is what a petrifying gaze forces.

BREATH class-attribute instance-attribute

BREATH = 'breath'

Breath attacks. A character's WIS modifier to saves against magic doesn't apply to this category.

SPELLS class-attribute instance-attribute

SPELLS = 'spells'

Spells, rods, and staves.

SaveResult

Bases: BaseModel

A saving throw's outcome: whether it passed, and the numbers behind it.

saving_throw returns one. Read passed to decide the consequence. The save changes nothing itself, so applying the consequence is up to you. The model is frozen.

passed instance-attribute

passed: bool

Whether the save succeeded.

auto class-attribute instance-attribute

auto: bool = False

Whether the target passed without a roll.

That happens when a monster's energy defense gives it an automatic save against a magical effect of that element, as a red dragon's does against a fire ball. When this is true, roll and required are None, and no draw was taken.

roll class-attribute instance-attribute

roll: int | None = None

The d20 as it landed, before modifiers, or None on an automatic save.

modifier class-attribute instance-attribute

modifier: int = 0

The sum of every modifier added to the roll, including the modifier you passed.

required class-attribute instance-attribute

required: int | None = None

The number roll plus modifier had to reach, or None on an automatic save.

events class-attribute instance-attribute

events: tuple[Event, ...] = ()

The save's SavingThrowRolledEvent, ready to append to your log.

TargetingMode

Bases: StrEnum

The ways select_targets chooses targets from a list of candidates.

Pass one to select_targets with the candidates it chooses from. A spell that targets creatures targets with one of these modes, and so does a breath weapon. osrlib.core doesn't work out who is in range, so you supply the candidates. Inside a session, osrlib.crawl.battle supplies them from the distances it tracks.

The values appear in events and stay fixed within a schema_version, the version stamp of the saved format.

SELF class-attribute instance-attribute

SELF = 'self'

The caster or user only. Put the caster first in the candidates, because select_targets takes the first one.

SINGLE class-attribute instance-attribute

SINGLE = 'single'

One creature: the first candidate.

UP_TO_N class-attribute instance-attribute

UP_TO_N = 'up_to_n'

The first N candidates in your order. N is fixed or rolled, like the 1d4 creatures of hold person.

HD_BUDGET class-attribute instance-attribute

HD_BUDGET = 'hd_budget'

Candidates taken weakest first until a Hit Dice budget runs out, the way sleep works.

select_targets skips a candidate with more Hit Dice than the budget has left, and goes on down the list.

AREA class-attribute instance-attribute

AREA = 'area'

Every candidate. Which creatures the area covers is yours to work out.

GAZE class-attribute instance-attribute

GAZE = 'gaze'

Every candidate, for a gaze that reaches every creature in melee with the gazer.

alignments_differ

alignments_differ(source: Creature, target: Creature) -> bool

Return whether two creatures have different alignments, in the sense a ward against another alignment uses.

Wards like protection from evil protect against creatures "of another alignment", and this function gives that answer. attack_roll and saving_throw call it for you, so you need it only when you write a ward of your own.

A creature with no alignment counts as being of another alignment, so the ward protects against it. A monster whose template lists several alignments has none when it was spawned without one chosen.

Parameters:

Name Type Description Default
source Creature

The creature the ward protects against, usually the attacker. A Creature, which a Character and a MonsterInstance both satisfy.

required
target Creature

The Creature the ward protects, a Character or a MonsterInstance.

required

Returns:

Type Description
bool

True when the alignments differ or either creature has no alignment.

Examples:

from osrlib.core.combat import alignments_differ
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
acolyte = spawn_monster(catalog.get("acolyte"), id="acolyte-1", stream=spawn)

assert goblin.alignment == "chaotic"
assert acolyte.alignment is None  # the acolyte lists several, and none was chosen
assert alignments_differ(goblin, acolyte)
assert not alignments_differ(goblin, goblin)

apply_healing

apply_healing(target: Creature, amount: int, *, source: str = 'magical') -> list[Event]

Restore hit points at once, up to the target's maximum.

This changes the target and draws nothing, so roll the amount first when the healing is rolled. Use it for a cure spell or a healing potion. For a day of rest, call natural_healing instead, which rolls the 1d3 and applies the diseases that slow it. A regenerating monster heals through its effect in the EffectsLedger, which doesn't call this function.

Some targets heal less or not at all:

  • A dead target can't be healed, and the call returns no events.
  • A target with the diseased condition, as from mummy rot, heals nothing from a magical source. Healing that's instant counts as magical, which is why magical is the default.
  • A target with the weakened condition, which follows being raised from the dead, heals nothing from any source until the weakness effect ends. The rules say the subject "has 1 hit point" until the recovery period ends, and that it "may not be shortened by any magical healing".
  • A target with a magical_healing_half modifier, as from a cursed scroll, heals half of a magical amount, rounded down.

A target that heals nothing because of a condition gets a HealingAppliedEvent with the code combat.healing.blocked, which reports 0 healed.

Parameters:

Name Type Description Default
target Creature

The Creature to heal, which a Character and a MonsterInstance both satisfy. The function changes it in place.

required
amount int

The hit points to restore, 0 or more. The function cuts healing past the maximum to the maximum, and doesn't treat it as an error.

required
source str

The kind of healing: magical, the default, natural, or regeneration. It decides which conditions block the healing, and appears in the event.

'magical'

Returns:

Type Description
list[Event]

A HealingAppliedEvent with the hit points actually restored, then a HitPointsReportedEvent. A blocked target gets only the blocked HealingAppliedEvent. A dead target gets an empty list.

Raises:

Type Description
ValueError

If amount is negative. The function changes nothing first.

Examples:

from osrlib.core.combat import DamageSource, apply_healing, deal_damage
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
deal_damage(goblin, 3, source=DamageSource())
assert (goblin.current_hp, goblin.max_hp) == (2, 5)

events = apply_healing(goblin, 10)
assert events[0].amount == 3  # capped at the maximum, not 10
assert goblin.current_hp == 5

attack_facet

attack_facet(attack: Attack) -> WeaponTemplate | CombatFacet | None

Return the damage dice, qualities, and ranges behind any attack.

Use it to read those stats without checking which form of Attack you have. It returns a weapon as it is, a gear item's combat field, and a magic weapon's base weapon. The functions that resolve attacks read these stats themselves, so you need this function to show an attack's stats or to choose between attacks, not to resolve one.

Parameters:

Name Type Description Default
attack Attack

The Attack: a weapon, a combat facet, a gear item, a monster attack, a magic item, or None for unarmed.

required

Returns:

Type Description
WeaponTemplate | CombatFacet | None

The stats, as a WeaponTemplate or a CombatFacet. None for an unarmed attack, a monster attack, a gear item with no combat stats, and a magic item with no base weapon, which is most magic items: armour, rings, potions, and the rest. A monster attack has its damage on the MonsterAttack itself.

Examples:

from osrlib.core.combat import attack_facet
from osrlib.data import load_equipment

catalog = load_equipment()
assert attack_facet(catalog.get("sword")).damage == "1d8"
assert attack_facet(catalog.get("oil_flask")).damage == "1d8"  # the gear item's facet
assert attack_facet(catalog.get("torch")).damage == "1d4"
assert attack_facet(None) is None  # unarmed: damage_roll rolls 1d2 for it

attack_roll

attack_roll(
    attacker: Combatant,
    defender: Combatant,
    attack: Attack,
    *,
    context: AttackContext,
    ruleset: Ruleset,
    stream: RngStream
) -> AttackRollResult

Roll an attack: 1d20 plus modifiers against the defender's armour class.

This is the first step of resolve_attack, which is what you usually call: it rolls the attack, checks the defender's immunities, rolls the damage, and applies it. Call attack_roll on its own when you want only whether the attack hits, as for an attack whose effect isn't damage. It changes nothing.

The roll adds every modifier that applies:

  • In melee, the attacker's STR modifier. With a missile, its DEX modifier, the range modifier from the context's distance_feet, and, for a halfling attacker, the halfling's missile bonus.
  • A thief's back-stab bonus, when the context sets both behind_target and target_unaware. The event's back_stab field is then true, on an automatic hit too.
  • +2 against a retreating defender.
  • A magic weapon's attack bonus, or its bonus against the kind of monster it's made against.
  • Spell bonuses on the attacker, like bless, and penalties from wards on the defender, like protection from evil.
  • The context's situational_modifier.

The function adjusts the defender's armour class too. The defender's shield doesn't count against an attack from behind, or while the defender retreats, and a magic shield's enchantment doesn't count either. The context's defender_ally_ac_bonus, an armour class bonus that an ally gives the defender, does count.

A melee attack hits a paralysed, asleep, or petrified defender automatically, with no roll. So does any attack on a monster whose template has no armour class, like green slime and yellow mould.

The attack hits when the d20 plus the modifiers reaches the total needed. The total needed comes from the B/X attack table, or from THAC0 − AC with no limits under the thac0_arithmetic ruleset flag. Armour class counts down in B/X, so a lower armour class is better and needs a higher roll. A natural 20 always hits and a natural 1 always misses.

Parameters:

Name Type Description Default
attacker Combatant

The attacking Combatant, which a Character and a MonsterInstance both satisfy.

required
defender Combatant

The defending Combatant, a Character or a MonsterInstance.

required
attack Attack

The Attack, or None for unarmed.

required
context AttackContext

The attack's context.

required
ruleset Ruleset

The ruleset in play.

required
stream RngStream

The stream to draw the d20 from, usually COMBAT_STREAM from your RngStreams. One draw for a rolled attack, and none for an automatic hit.

required

Returns:

Type Description
AttackRollResult

The roll's outcome. Read hit to decide what happens next. roll is the d20 as it landed, total is roll plus the modifiers, and required is the total needed. roll is None on an automatic hit. events contains the AttackRolledEvent, with the code combat.attack.hit, combat.attack.missed, or combat.attack.auto_hit.

Raises:

Type Description
ValueError

If the defender has no armour_class attribute, which means it isn't a combatant. The function makes no random roll first.

Examples:

from osrlib.core.combat import COMBAT_STREAM, AttackContext, attack_roll
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

streams = RngStreams(master_seed=5)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
orc = spawn_monster(catalog.get("orc"), id="orc-1", stream=spawn)

rolled = attack_roll(
    goblin,
    orc,
    load_equipment().get("sword"),
    context=AttackContext(situational_modifier=-2),  # the orc has cover
    ruleset=Ruleset(),
    stream=streams.get(COMBAT_STREAM),
)
assert (rolled.roll, rolled.modifier, rolled.total) == (16, -2, 14)
assert rolled.required == 13
assert rolled.hit
assert rolled.natural is None  # no natural 1 or 20 overrode the arithmetic

burning_oil_pool_definition

burning_oil_pool_definition() -> EffectDefinition

Build the effect for a pool of burning oil, which burns in one place for one turn.

A flask of oil thrown unlit does no damage. Instead it spills into a pool, and someone can set the pool alight. A lit pool burns for one turn, which is ten minutes of game time, and deals 1d8 fire damage to each creature that passes through it. osrlib doesn't track where creatures walk, so you decide who passes through and apply the damage with deal_damage. The effect only marks the burning pool and when it goes out.

The function takes no arguments because the pool is the same every time: 1d8 fire damage in a 3-foot radius for one turn. Attach the effect to a location string with EffectsLedger.attach.

Returns:

Type Description
EffectDefinition

The one-turn EffectDefinition, whose params contain the dice, the element, and the radius in feet.

Examples:

from osrlib.core.combat import burning_oil_pool_definition

pool = burning_oil_pool_definition()
assert pool.kind == "burning_oil_pool"
assert pool.duration_unit == "turn"
assert pool.params == {"dice": "1d8", "element": "fire", "radius_feet": 3}

cannot_move

cannot_move(combatant: Creature) -> bool

Return whether a creature can't move.

Ask this before you let a creature move, flee, or close to melee. It's true for an incapacitated creature, which is dead, paralysed, turned to stone, or asleep, and for an entangled one, which is caught in a web. Nothing in this module moves creatures, so no function here calls it for you.

Parameters:

Name Type Description Default
combatant Creature

The Creature to ask about, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
bool

True when the creature can't move.

Examples:

from osrlib.core.combat import cannot_move
from osrlib.core.effects import Condition, grant_condition
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
assert not cannot_move(goblin)

grant_condition(goblin, Condition.ENTANGLED, None)  # a web caught it
assert cannot_move(goblin)

check_immunity

check_immunity(defender: Creature, source: DamageSource, *, ruleset: Ruleset, attacker: Creature | None = None) -> bool

Return True when the defender is immune to the damage source, so no damage is rolled.

osrlib calls this the immunity check. resolve_attack runs it on every hit, and resolve_breath runs it for every target. Call it yourself to ask whether a weapon can hurt a monster before the party spends rounds finding out. Build the source with damage_source_for. deal_damage doesn't run this check.

The defender is immune in these cases:

  • It's a monster that only some materials can harm, and the source has none of them. A steel sword can't harm a werewolf, and a silver dagger can.
  • The source's keys include holy, and the defender isn't undead. Holy water has that key. It harms only the undead, and it gets past any material defense an undead monster has.
  • It's a monster that uses fire, and the source is burning oil.
  • It's a monster with an energy defense against the source's element. When the defense covers every source of the element, the monster takes no damage from it. When the defense covers only nonmagical sources, as a red dragon's does against fire, a source whose magical is True still harms the monster.
  • It's under protection from normal missiles, and the source is a small nonmagical missile. An arrow or a thrown flask is blocked, and a hurled boulder or a magic arrow isn't.

The hd5_counts_as_magical ruleset flag is off by default. With it on, two kinds of monster can harm a monster that only silver or magic can harm:

  • A monster with 5 or more Hit Dice. A monster that energy drain has taken Hit Dice from counts only the Hit Dice it has left.
  • A monster that only silver or magic can harm itself.

The rule applies only when you pass the attacking monster as attacker.

Parameters:

Name Type Description Default
defender Creature

The defending Creature, which a Character and a MonsterInstance both satisfy.

required
source DamageSource

The damage source.

required
ruleset Ruleset

The ruleset in play.

required
attacker Creature | None

The attacking Creature, a Character or a MonsterInstance. The function reads it only for the hd5_counts_as_magical rule, and without it that rule doesn't apply.

None

Returns:

Type Description
bool

True when the defender is immune and no damage should be rolled.

Examples:

from osrlib.core.combat import AttackContext, check_immunity, damage_source_for
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
werewolf = spawn_monster(catalog.get("werewolf"), id="werewolf-1", stream=spawn)

equipment = load_equipment()
rules = Ruleset()
steel = damage_source_for(goblin, equipment.get("sword"), AttackContext())
silver = damage_source_for(goblin, equipment.get("silver_dagger"), AttackContext())

assert check_immunity(werewolf, steel, ruleset=rules)  # the werewolf shrugs off steel
assert not check_immunity(werewolf, silver, ruleset=rules)

check_morale

check_morale(subject: str, score: int, *, modifier: int = 0, stream: RngStream) -> MoraleResult

Check a side's morale: 2d6 against its morale score, where a roll over the score breaks it.

Call this when a side must check morale, and act on the result yourself: this function doesn't make anyone flee or surrender. morale_triggers tells you when a side must check. To apply the rule that a side which holds twice stops checking, call MoraleTracker.check instead. A monster's morale score, ML on its stat block, is the morale field of its template.

The check is for a side, not a creature. A spell like bless changes a creature's morale, so read that change with morale_modifier and add it to the modifier you pass. A side with a score of 2 or less never fights, and a side with 12 or more never checks. Both are exempt: the function makes no roll, takes no draw, and ignores the modifier.

Parameters:

Name Type Description Default
subject str

The side's key. It appears in the event, so you can show which side checked.

required
score int

The morale score, which is 2 to 12 on a stat block. The function accepts any integer. A side with a score of 2 or less never fights, and a side with 12 or more always does.

required
modifier int

The adjustment to the roll. A value outside −2 to +2 counts as −2 or +2.

0
stream RngStream

The stream the 2d6 comes from, usually COMBAT_STREAM. Two draws for a rolled check, and none for an exempt one.

required

Returns:

Type Description
MoraleResult

The outcome. Its MoraleCheckedEvent has the verdict in held for every code, exempt checks included. The event is visible to the referee only, because players learn a side's morale from what it does.

Examples:

from osrlib.core.combat import COMBAT_STREAM, check_morale
from osrlib.core.rng import RngStreams

combat = RngStreams(master_seed=3).get(COMBAT_STREAM)

goblins = check_morale("goblins", 7, stream=combat)
assert goblins.roll == 8  # over their morale score of 7
assert not goblins.held

skeletons = check_morale("skeletons", 12, stream=combat)
assert skeletons.exempt and skeletons.held  # morale 12 never checks
assert skeletons.roll is None

damage_roll

damage_roll(
    attacker: Combatant,
    attack: Attack,
    *,
    context: AttackContext,
    ruleset: Ruleset,
    stream: RngStream,
    defender: Creature | None = None
) -> RollResult

Roll an attack's damage: the dice, the bonuses, and the multipliers, at least 1.

resolve_attack calls this after a hit gets past the defender's immunities, and passes the total to deal_damage. Call it yourself to preview a weapon's damage, or to apply the damage some other way. It only rolls: the defender loses nothing here, and deal_damage applies the defender's reductions later.

The total adds these, in this order:

  1. The attack's dice. A monster attack with a fixed amount rolls no dice.
  2. The attacker's STR modifier, on a melee attack that isn't a monster attack.
  3. A magic weapon's damage bonus. Some magic weapons have a separate bonus against certain monsters. When defender is one of those monsters, the function adds that bonus instead of the weapon's usual damage bonus.
  4. Spell bonuses, like bless. On a weapon attack, striking adds an extra die.
  5. The multipliers. Each one multiplies the total so far:
    • ×2 for a weapon with the brace quality, like a spear, set against a charge. The context's braced says so.
    • ×2 for a charge with a weapon that has the charge quality, like a lance. The context's charging says so.
    • Magic like a potion of giant strength or of growth.
    • A thief's back-stab, when the context sets behind_target and target_unaware.

The total is at least 1, except for a monster attack that deals no hit point damage, like a wight's touch, which totals 0.

With the variable_weapon_damage ruleset flag off, every weapon and every gear item with combat stats deals 1d6 instead of its listed dice. An unarmed attack still deals 1d2, and a monster attack still deals its listed damage. A Girdle of Giant Strength doubles weapon damage with the flag on, and deals its listed 2d8 with the flag off.

Parameters:

Name Type Description Default
attacker Combatant

The attacking Combatant, which a Character and a MonsterInstance both satisfy.

required
attack Attack

The Attack, or None for unarmed.

required
context AttackContext

The attack's context. Step 5 reads its braced, charging, behind_target, and target_unaware fields. For a monster attack with more than one fixed amount, its fixed_damage_option picks the amount, and it must be an index into the attack's fixed_damage_options.

required
ruleset Ruleset

The ruleset in play.

required
stream RngStream

The stream to draw the damage dice from, usually COMBAT_STREAM.

required
defender Creature | None

The defending Creature, a Character or a MonsterInstance. The function reads it only for a magic weapon with a bonus against certain monsters.

None

Returns:

Type Description
RollResult

The damage roll. total is the damage to pass to deal_damage. rolls contains each die, including the extra die of striking. modifier is the sum of every flat amount: the bonuses in steps 2 to 4, any modifier in the dice expression, and a monster attack's fixed amount. multiplier is the product of the multipliers in step 5. So total is (sum(rolls) + modifier) * multiplier, with the floor described above.

Raises:

Type Description
ValueError

If the attack has no combat stats to roll damage from: a gear item like a lantern, or a magic item with no base weapon, like Armour +1. Also if the context's fixed_damage_option isn't an index into a monster attack's fixed_damage_options, counting from 0. The function raises before it draws.

Examples:

from osrlib.core.combat import COMBAT_STREAM, AttackContext, damage_roll
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)

rolled = damage_roll(
    goblin,
    load_equipment().get("sword"),
    context=AttackContext(),
    ruleset=Ruleset(),
    stream=streams.get(COMBAT_STREAM),
)
assert rolled.rolls == (5,)  # one d8
assert rolled.total == 5  # a goblin adds no strength modifier

damage_source_for

damage_source_for(attacker: Creature, attack: Attack, context: AttackContext) -> DamageSource

Build the damage source of an attack, for checking against the defender's defenses.

resolve_attack builds one for you on every hit. Call this function yourself to ask check_immunity whether an attack can harm a defender before the party spends a round finding out. For damage that isn't an attack, like a trap or a spell, construct a DamageSource yourself.

What each attack's source has:

  • A silver weapon has the silver key, and a magic weapon has magic.
  • Holy water has holy.
  • A torch, and an oil flask with lit set in the context, deal fire. Fire counts against a troll's regeneration.
  • A weapon, but not an unarmed strike, has magic while its wielder is under the striking spell.
  • A monster attack has no keys, and its kind is monster.
  • The function marks a missile weapon used at a distance, and thrown oil or holy water, as a small missile. It marks a monster attack only when the context's monster_missile is true.

The hd5_counts_as_magical ruleset flag lets a strong monster harm monsters that only silver or magic can harm. check_immunity applies it from the attacker, so this function doesn't.

Parameters:

Name Type Description Default
attacker Creature

The attacking Creature, which a Character and a MonsterInstance both satisfy.

required
attack Attack

The Attack, or None for unarmed.

required
context AttackContext

The attack's context. Its lit field is whether an oil flask is alight, and its distance_feet sets whether a melee-and-missile weapon is thrown.

required

Returns:

Type Description
DamageSource

The frozen damage source, ready for check_immunity and deal_damage.

Examples:

from osrlib.core.combat import AttackContext, damage_source_for
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_equipment, load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
catalog = load_equipment()

silver = damage_source_for(goblin, catalog.get("silver_dagger"), AttackContext())
assert silver.keys == ("silver",)

oil = damage_source_for(goblin, catalog.get("oil_flask"), AttackContext(lit=True))
assert (oil.element, oil.kind, oil.missile) == ("fire", "splash", True)

fist = damage_source_for(goblin, None, AttackContext())
assert fist.kind == "unarmed"

deal_damage

deal_damage(
    target: Combatant,
    amount: int,
    *,
    source: DamageSource,
    attacker_id: str | None = None,
    rolls: tuple[int, ...] = (),
    clock: GameClock | None = None,
    ruleset: Ruleset | None = None,
    stream: RngStream | None = None
) -> list[Event]

Apply damage to a creature: its reductions, its hit points, and its death.

This changes the target. resolve_attack calls it for you on a hit. Call it yourself for damage that isn't an attack, like a trap, a spell, or a fall, whose dice falling_damage rolls. Roll the amount first, with damage_roll or roll, and describe where it comes from with a DamageSource. This function draws no dice unless a destructive source kills a target that carries magic items.

It doesn't check immunity. A monster that only silver or magic can harm takes the damage anyway, so call check_immunity first when the source is one its defenses should stop.

It works in this order:

  1. The target's reductions that divide damage apply, like the wraith's half damage from silver and the mummy's half damage from everything. Each one leaves at least 1.
  2. Reductions for the source's element apply, like resist fire. Each takes 1 point off each die in rolls and leaves every die at least 1, so damage with no rolls isn't reduced.
  3. The hit points come off, stopping at 0. When you pass a clock, the function records the round in a MonsterInstance's last_damaged_round. A troll's regeneration waits after that round, and a dead troll gets back up 2d6 rounds after it.
  4. Damage that stops the target's regeneration adds to its nonregen_damage. The paragraph after this list explains it.
  5. At 0 hit points the target dies, through kill. A monster that regenerates after death dies for good only when its nonregen_damage reaches its maximum hit points. Then a destructive source destroys what the target carried, through destroy_equipment.

Fire and acid stop a troll's regeneration, and the regeneration of a character who wears a ring of regeneration. The function adds such damage to the target's nonregen_damage, up to its maximum hit points. Regeneration never heals that damage.

Other healing, like a potion, does heal it. So before each hit on a target that regenerates, the function lowers nonregen_damage to no more than the damage the target has now, its maximum hit points less its current hit points. For example, a troll with 30 maximum hit points takes 10 fire damage, so its nonregen_damage is 10. A potion heals it to 26 hit points. On the next hit, nonregen_damage first drops to 4.

A target that's already dead doesn't die again. When the damage makes a dead troll's death permanent, a DeathEvent with the code combat.death.permanent reports it.

Parameters:

Name Type Description Default
target Combatant

The Combatant taking the damage, which a Character and a MonsterInstance both satisfy. The function changes it in place. Its saving throws are what its magic items save against when a destructive source kills it.

required
amount int

The damage rolled, before reductions. Zero or more. To give back hit points, call apply_healing.

required
source DamageSource

Where the damage comes from. Which reductions apply, whether the damage counts against regeneration, and whether a kill destroys equipment all depend on it.

required
attacker_id str | None

The attacker's entity id, for the event. None when there's no attacker.

None
rolls tuple[int, ...]

The damage dice as rolled. They appear in the event and set how much a reduction per die can take.

()
clock GameClock | None

The game clock. When you pass it, the function sets a monster's last_damaged_round.

None
ruleset Ruleset | None

The ruleset in play. Whether magic items save when a destructive source kills the target depends on it.

None
stream RngStream | None

The stream the magic items' saves draw from, which is the stream of whatever is resolving the damage. It's needed only when a destructive source kills a target that carries magic items and the ruleset has the saves on.

None

Returns:

Type Description
list[Event]

The events in order, ready to append to your log: a DamageDealtEvent and a HitPointsReportedEvent, then the events of kill when the damage kills the target, and last an EquipmentDestroyedEvent when a destructive source killed a target that carried something.

Raises:

Type Description
ValueError

If amount is negative, or if a destructive source kills a target that carries a magic item, the ruleset's magic_item_death_save is on, and you passed no stream. The target doesn't change.

Examples:

from osrlib.core.combat import DamageSource, deal_damage
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
assert goblin.current_hp == 5

events = deal_damage(goblin, 2, source=DamageSource(kind="falling"), attacker_id=None)
assert [event.code for event in events] == ["combat.damage.dealt", "combat.state.hit_points"]
assert goblin.current_hp == 3

events = deal_damage(goblin, 99, source=DamageSource(kind="falling"))
assert "combat.death.died" in [event.code for event in events]
assert goblin.current_hp == 0  # hit points floor at 0, they never go negative

destroy_equipment

destroy_equipment(
    target: Combatant,
    *,
    source: DamageSource | None = None,
    ruleset: Ruleset | None = None,
    stream: RngStream | None = None
) -> list[Event]

Destroy everything a victim carries, as a breath weapon or disintegrate does when it kills.

deal_damage calls this when a destructive source kills its target, so you rarely call it yourself. cast_spell calls it directly for disintegrate, because the spell destroys the victim and what it carried without dealing damage.

Under the magic_item_death_save ruleset flag, which is on by default, each magic item the victim carries gets a saving throw. The function rolls 1d20 for each item. The item saves on the victim's target number in the category that matches the source: versus breath for a breath weapon, versus spells for a spell, versus wands for a device, and versus death for anything else. The roll adds the item's best bonus, the highest of its attack, damage, and armour class bonuses, so a cursed item saves at its penalty. The items that save stay in the inventory's items list, no longer equipped. The saving throws report no events of their own. The function returns one EquipmentDestroyedEvent, which lists the items destroyed and the items saved. In a GameSession, that event's page says where a dead party member's saved items go.

Parameters:

Name Type Description Default
target Combatant

The victim, a Combatant, which a Character and a MonsterInstance both satisfy. The function empties its inventory except for the magic items that saved, and leaves nothing wielded, worn, or on its fingers.

required
source DamageSource | None

The destructive damage source, whose kind picks the saving throw category. With None, the items save versus death.

None
ruleset Ruleset | None

The ruleset in play. With None, the function skips the saves and destroys every item.

None
stream RngStream | None

The stream the items' saves draw from, one draw for each magic item.

None

Returns:

Type Description
list[Event]

A list with one EquipmentDestroyedEvent, which lists the destroyed items and the saved ones. An empty list when the victim carries nothing.

Raises:

Type Description
ValueError

If the saves are on, the victim carries a magic item, and you passed no stream. The function changes nothing first.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.combat import COMBAT_STREAM, DamageSource, destroy_equipment
from osrlib.core.items import MagicItemInstance
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset

rules = Ruleset()
streams = RngStreams(master_seed=3)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
    purchases=[("torch", 1)],
).character
hild.inventory.items.append(MagicItemInstance(instance_id="item-1", template_id="sword_plus_1"))

breath = DamageSource(element="fire", kind="breath", destructive=True)
events = destroy_equipment(hild, source=breath, ruleset=rules, stream=streams.get(COMBAT_STREAM))
assert events[0].item_names == ("Torches (6)",)
assert events[0].saved_items == ("item-1",)  # the Sword +1 made its save versus breath
assert [item.instance_id for item in hild.inventory.items] == ["item-1"]

drain_monster_hd

drain_monster_hd(monster: MonsterInstance, *, levels: int = 1, stream: RngStream) -> list[Event]

Drain Hit Dice from a monster, which is how energy drain works on a monster.

The rules say energy drain takes "one experience level (or Hit Die)": a character loses levels and a monster loses Hit Dice. Call this when something drains a monster. For a character, call drain_levels. resolve_energy_drain calls the right one of the two for you after an undead creature's hit. This function changes the monster.

A drain that would take a monster's last Hit Die kills it. The function rolls no d8 for that Hit Die, but counts it as lost. So a 1 HD monster drained of one level reports 1 level lost and a new level of 0.

Every other Hit Die drained takes a rolled d8 from both the monster's maximum and its current hit points. Its THAC0 and saving throws become those of its new Hit Dice. Neither hit point total falls below 1, so the lost hit points alone never kill a monster.

The function reports the drain as a LevelDrainedEvent. Its hp_lost is how far the monster's maximum hit points fell. When the floor of 1 stops the loss, hp_lost is less than the total of the d8s rolled.

Parameters:

Name Type Description Default
monster MonsterInstance

The drained MonsterInstance. The function changes it in place.

required
levels int

How many Hit Dice the drain takes, 1 or more.

1
stream RngStream

The stream the d8s for lost hit points come from, usually ADVANCEMENT_STREAM. One draw for each Hit Die taken, and none for the Hit Die that kills.

required

Returns:

Type Description
list[Event]

For a monster that survives, a LevelDrainedEvent with the code combat.drain.drained, then a HitPointsReportedEvent. For a monster the drain kills, a LevelDrainedEvent with the code combat.drain.slain, then the events of kill, which end with a HitPointsReportedEvent that reports 0.

Raises:

Type Description
ValueError

If levels is less than 1. Nothing changes and the stream doesn't advance.

Examples:

from osrlib.core.character import ADVANCEMENT_STREAM
from osrlib.core.combat import drain_monster_hd
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
ogre = spawn_monster(load_monsters().get("ogre"), id="ogre-1", stream=spawn)
assert (ogre.hit_dice_count, ogre.max_hp, ogre.thac0) == (4, 25, 15)

events = drain_monster_hd(ogre, stream=streams.get(ADVANCEMENT_STREAM))
assert events[0].code == "combat.drain.drained"
# Fewer Hit Dice and hit points, and a worse THAC0.
assert (ogre.hit_dice_count, ogre.max_hp, ogre.thac0) == (3, 21, 16)

effective_hd

effective_hd(combatant: Creature) -> int

Return how many Hit Dice a creature counts as when a spell like sleep spends a Hit Dice budget.

select_targets spends its hd_budget in these units. Call this function yourself to work out in advance how many creatures a sleep would take.

A monster counts its Hit Dice without the hit point bonus after them, so a 2+1 HD monster counts as 2. A monster that energy drain has taken Hit Dice from counts the Hit Dice it has left, its hit_dice_count. A monster under 1 Hit Die counts as 1. A character counts its level.

Parameters:

Name Type Description Default
combatant Creature

The Creature to measure, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
int

The Hit Dice the creature counts as, at least 1.

Examples:

from osrlib.core.combat import effective_hd
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()

assert effective_hd(spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)) == 1
assert effective_hd(spawn_monster(catalog.get("ogre"), id="ogre-1", stream=spawn)) == 4  # 4+1 HD
assert effective_hd(spawn_monster(catalog.get("normal_rat"), id="rat-1", stream=spawn)) == 1  # under 1 HD

falling_damage

falling_damage(feet: int, stream: RngStream) -> RollResult | None

Roll falling damage: 1d6 for each full 10 feet fallen.

This only rolls. Apply the total with deal_damage, passing a DamageSource whose kind is falling, and the roll's rolls. deal_damage doesn't check immunity, so a monster that only silver or magic can harm takes the fall too. Its damage reductions still apply.

Parameters:

Name Type Description Default
feet int

The distance fallen. A part of 10 feet doesn't count, so 19 feet is one die.

required
stream RngStream

The stream the d6s come from, usually COMBAT_STREAM.

required

Returns:

Type Description
RollResult | None

The damage roll, or None for a fall under 10 feet, for which the function rolls no dice and takes no draw.

Examples:

from osrlib.core.combat import COMBAT_STREAM, falling_damage
from osrlib.core.rng import RngStreams

combat = RngStreams(master_seed=3).get(COMBAT_STREAM)

rolled = falling_damage(25, combat)
assert rolled.rolls == (5, 3)  # two dice: 25 feet is two full ten-foot drops
assert rolled.total == 8

assert falling_damage(8, combat) is None

incapacitated

incapacitated(combatant: Creature) -> bool

Return whether a creature is out of the fight: dead, paralysed, turned to stone, or asleep.

morale_triggers counts a side's incapacitated members with this, and resolve_gaze skips them. Call it yourself to ask whether a creature is out of the fight, whichever way it went out. To ask whether it can still move, call cannot_move, which also counts a creature caught in a web.

The tabletop rules count a side's members who are "slain, paralysed, etc" for morale. osrlib reads that as dead, paralysed, petrified, or asleep.

Parameters:

Name Type Description Default
combatant Creature

The Creature to ask about, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
bool

True when the creature has any of those conditions.

Examples:

from osrlib.core.combat import DamageSource, deal_damage, incapacitated
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
assert not incapacitated(goblin)

deal_damage(goblin, 99, source=DamageSource())
assert incapacitated(goblin)

melee_modifier_for

melee_modifier_for(combatant: Combatant) -> int

Return the modifier a combatant adds to melee attack rolls and melee damage.

attack_roll and damage_roll add it themselves on every melee attack. Call it to show a character's melee bonus or to preview a swing. Don't add it to the situational_modifier of an attack, or it counts twice.

It's the combatant's melee_modifier. A character's is Character.melee_modifier, which comes from STR. For a character who wears gauntlets of ogre power, it's the modifier for STR 18, which is +3. Under the curse of a ring of weakness, it's the modifier for STR 3, which is −3. A monster has no STR score, so its modifier is 0.

Parameters:

Name Type Description Default
combatant Combatant

The attacking Combatant, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
int

The modifier, from −3 to +3.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.combat import melee_modifier_for
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_monsters

streams = RngStreams(master_seed=17)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character
assert melee_modifier_for(hild) == 2  # this Hild rolled STR 16

goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=streams.get(MONSTER_SPAWN_STREAM))
assert melee_modifier_for(goblin) == 0

morale_modifier

morale_modifier(combatant: Creature) -> int

Return the change that spells like bless and blight make to a creature's morale.

check_morale takes a side's key and score, not a creature, so it applies a spell's morale change only when you pass it. Read the change here and add it to the modifier you pass to check_morale. It then counts like any other adjustment: the total is limited to −2 to +2, and it doesn't apply to an exempt side, at morale 2 or less or 12 or more.

Parameters:

Name Type Description Default
combatant Creature

The Creature whose morale is being checked, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
int

The sum of the morale changes from every effect on the creature, and 0 when there are none. It can be negative.

Examples:

from osrlib.core.combat import COMBAT_STREAM, check_morale, morale_modifier
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
assert morale_modifier(goblin) == 0  # nothing has blessed or blighted it

outnumbered = -1
adjustment = outnumbered + morale_modifier(goblin)
checked = check_morale("goblins", 7, modifier=adjustment, stream=streams.get(COMBAT_STREAM))
assert checked.modifier == -1
assert checked.roll == 8 and checked.held  # 8 - 1 is within the morale score of 7

morale_triggers

morale_triggers(members: Sequence[Creature]) -> list[str]

Return the reasons a side must check morale, from the state of its members now.

Call this after each round to learn whether a side should check morale. Then call check_morale or MoraleTracker.check for the check itself. In a session, osrlib.crawl.battle does this for you. The reasons, which osrlib calls triggers, are first_death, when any member of the side is dead, and half_incapacitated, when half the side or more is dead, paralysed, turned to stone, or asleep.

The triggers describe the side as it is now, not what changed since you last asked, so every call returns first_death while a member lies dead. Keep track of the triggers you've already acted on.

Parameters:

Name Type Description Default
members Sequence[Creature]

The side's creatures, each a Creature, which a Character and a MonsterInstance both satisfy.

required

Returns:

Type Description
list[str]

The triggers: first_death when any member is dead, and half_incapacitated when half the side or more is incapacitated. When both apply, first_death comes first. The list is empty when neither applies, and for an empty side.

Examples:

from osrlib.core.combat import DamageSource, deal_damage, morale_triggers
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
first = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
second = spawn_monster(catalog.get("goblin"), id="goblin-2", stream=spawn)
assert morale_triggers([first, second]) == []

deal_damage(first, 99, source=DamageSource())
assert morale_triggers([first, second]) == ["first_death", "half_incapacitated"]

natural_healing

natural_healing(target: Creature, stream: RngStream, *, ledger: EffectsLedger | None = None) -> list[Event]

Heal one full day of complete rest: 1d3 hit points.

Call this once for each day of rest without interruption. You decide whether the rest was interrupted. In a session, the rest procedure decides it for you. For healing from a spell or a potion, call apply_healing instead, which takes the amount you rolled.

An effect that slows healing makes the target heal less often, not heal less. Mummy rot makes natural healing ten times slower, so the target heals on every tenth day of rest. With an effect that has a healing_rest_days param, the target heals once in that many days of rest, which is 2 for cause disease and for a cursed scroll's "twice the usual amount of time". The function counts the days in the effect's state, and when several effects apply, the slowest one counts. A diseased target doesn't heal at all when you pass no ledger.

Parameters:

Name Type Description Default
target Creature

The resting Creature, which a Character and a MonsterInstance both satisfy. The function changes it in place.

required
stream RngStream

The stream the 1d3 comes from. Natural healing draws from EFFECTS_STREAM, with the draws for effects, not from the combat stream. One draw on a day the target heals, and none on a day it doesn't.

required
ledger EffectsLedger | None

The EffectsLedger that contains the target's effects. Without it, no effect can slow the healing.

None

Returns:

Type Description
list[Event]

The events of apply_healing for the 1d3. An empty list on a day an effect skips, and for a dead target.

Examples:

from osrlib.core.combat import DamageSource, deal_damage, natural_healing
from osrlib.core.effects import EFFECTS_STREAM
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
deal_damage(goblin, 4, source=DamageSource())
assert goblin.current_hp == 1

events = natural_healing(goblin, streams.get(EFFECTS_STREAM))
assert events[0].amount == 1  # the 1d3 came up 1
assert goblin.current_hp == 2

participant_modifier

participant_modifier(combatant: Combatant, *, monster_modifier: int = 0) -> int

Return a combatant's modifier to an individual initiative roll.

Use it to fill the modifier field of a Participant before you call roll_initiative. The modifier counts only when the individual_initiative ruleset flag is on. Side initiative, the default, rolls once for each side and adds no modifier.

A character gets its DEX modifier, plus 1 for a halfling. A monster gets monster_modifier, because the tabletop rules leave a monster's initiative modifier to the referee.

Parameters:

Name Type Description Default
combatant Combatant

The Combatant rolling, which a Character and a MonsterInstance both satisfy.

required
monster_modifier int

The modifier to use for a monster. The function ignores it for a character.

0

Returns:

Type Description
int

The modifier to put in the Participant's modifier field. It can be negative.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.combat import participant_modifier
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_monsters

streams = RngStreams(master_seed=9)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character
assert participant_modifier(hild) == 1  # this Hild rolled DEX 17

goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=streams.get(MONSTER_SPAWN_STREAM))
assert participant_modifier(goblin) == 0
assert participant_modifier(goblin, monster_modifier=1) == 1

resolve_attack

resolve_attack(
    attacker: Combatant,
    defender: Combatant,
    attack: Attack,
    *,
    context: AttackContext,
    ruleset: Ruleset,
    stream: RngStream,
    clock: GameClock | None = None
) -> AttackResult

Resolve one attack from start to finish: the roll, the immunity check, and the damage.

This is the function you usually need. It rolls the attack, checks whether the defender is immune, rolls the damage, and applies it. It changes the defender, so the hit points are already gone when you read the result. To check first whether the attack is allowed, call validate_attack, which draws nothing and changes nothing.

Other attacks have separate functions:

The steps always run in this order. First the attack roll, through attack_roll. On a hit, check_immunity: when the defender is immune, the function rolls no damage, and a DamageAbsorbedEvent reports the hit. Otherwise damage_roll rolls the damage and deal_damage applies it.

Three hits end early:

  • A sleeping defender hit in melee with a bladed weapon dies at once, with no damage rolled. The immunity check still comes first.
  • An oil flask thrown unlit does nothing and reports 0 damage. To have it burn on the ground instead, attach the effect from burning_oil_pool_definition.
  • A monster attack that deals no hit point damage, like a wight's touch, reports 0 damage and applies none.

Parameters:

Name Type Description Default
attacker Combatant

The attacking Combatant, which a Character and a MonsterInstance both satisfy.

required
defender Combatant

The defending Combatant, a Character or a MonsterInstance. The function changes it in place when damage lands.

required
attack Attack

The Attack, or None for unarmed.

required
context AttackContext

The attack's context. AttackContext() is the plain melee case.

required
ruleset Ruleset

The ruleset in play.

required
stream RngStream

The stream every draw comes from, usually COMBAT_STREAM. The attack roll takes one draw, and none on an automatic hit. A hit that deals damage then takes one draw for each damage die, and more when the attacker is under striking.

required
clock GameClock | None

The game clock. When you pass it, the function sets a monster defender's last_damaged_round on a damaging hit, which delays a troll's regeneration.

None

Returns:

Type Description
AttackResult

The attack's outcome. attack_roll has the roll. absorbed is true when the defender was immune. damage is the damage rolled, before the defender's reductions, or None when none was rolled. events has every event the attack caused, in order. Its DamageDealtEvent has the hit points the defender lost, and the HitPointsReportedEvent after it has the hit points the defender has left. When the defender dies, the events of kill come next.

Raises:

Type Description
ValueError

If the attack can't deal damage: an attack with no combat stats, like a lantern or a wand, or a context whose fixed_damage_option isn't an index into the monster attack's fixed_damage_options. The function raises before the attack roll, so the stream doesn't advance and the defender doesn't change.

Examples:

A 1st-level fighter swings a sword at a goblin. Every draw comes from a named, seeded stream, so the same seed always replays the same fight:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.combat import COMBAT_STREAM, AttackContext, resolve_attack
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

rules = Ruleset()
streams = RngStreams(master_seed=7)
hild = create_character(
    name="Hild",
    class_id="fighter",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character
spawn = streams.get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)
sword = load_equipment().get("sword")

combat = streams.get(COMBAT_STREAM)
result = resolve_attack(hild, goblin, sword, context=AttackContext(), ruleset=rules, stream=combat)
assert result.events[0].code in ("combat.attack.hit", "combat.attack.missed")
assert result.attack_roll.hit  # seed 7 hits: 12 rolled + 1 = 13 against a required 13
assert result.damage == 9  # same seed, same damage roll
assert goblin.current_hp == 0
assert "combat.death.died" in [event.code for event in result.events]

resolve_breath

resolve_breath(
    monster: MonsterInstance,
    targets: Sequence[Combatant],
    *,
    ruleset: Ruleset,
    stream: RngStream,
    clock: GameClock | None = None
) -> list[Event]

Resolve a monster's breath weapon against the creatures you say it catches.

Call this instead of resolve_attack when a monster breathes. There's no attack roll: every target saves versus breath instead, and the whole breath resolves in one call. You supply the creatures caught in it, because osrlib.core has no record of where creatures stand. Call validate_breath first, because breathing past the daily limit raises an error instead of returning a rejection. This function adds one to the monster's daily count and changes every target it harms.

What the breath does depends on the monster:

  • A dragon's breath deals damage equal to the dragon's current hit points, so a wounded dragon's breath is weaker. A dragon breathes up to three times a day.
  • A hellhound's breath rolls its listed dice, with no daily limit. The function rolls the dice again for each target.
  • A sea dragon's spittle kills a target that fails its save, and does nothing to one that passes.

A target that saves takes half damage, rounded down, so a breath of 1 point does nothing to it. A target immune to the breath's element doesn't save and takes nothing.

A breath weapon is a destructive source, so a target it kills loses what it carried, and its magic items save under the magic_item_death_save ruleset flag. The tabletop rules give a lightning bolt and a dragon's breath as examples of deaths that destroy items. osrlib applies the rule to every breath weapon, so a hellhound's fire destroys equipment as a dragon's does.

Parameters:

Name Type Description Default
monster MonsterInstance

The breathing MonsterInstance. Its breath_uses_today goes up by one when its breath has a daily limit.

required
targets Sequence[Combatant]

The creatures caught in the breath, each a Combatant, which a Character and a MonsterInstance both satisfy. The function changes them in place.

required
ruleset Ruleset

The ruleset in play.

required
stream RngStream

The stream every draw comes from, usually COMBAT_STREAM: one save for each target, the damage dice when the breath rolls them, and the saves of the magic items of each target it kills.

required
clock GameClock | None

The game clock. When you pass it, the function sets the last_damaged_round of each monster target the breath damages.

None

Returns:

Type Description
list[Event]

The events for each target, in the order you passed the targets. A target immune to the breath gets a DamageAbsorbedEvent and doesn't save. Any other target gets its SavingThrowRolledEvent, then the events of deal_damage when damage lands, or of kill when the breath kills outright.

Raises:

Type Description
ValueError

If the monster has no breath weapon, or has used up its breath for the day. The function draws nothing and changes nothing first. Breathing anyway is a mistake in your code, not a move the rules reject, so call validate_breath first.

Examples:

from osrlib.core.combat import COMBAT_STREAM, resolve_breath
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
dragon = spawn_monster(catalog.get("white_dragon"), id="dragon-1", stream=spawn)
goblins = [spawn_monster(catalog.get("goblin"), id=f"goblin-{n}", stream=spawn) for n in (1, 2)]
assert dragon.current_hp == 39  # the cone deals this much, halved on a save

events = resolve_breath(dragon, goblins, ruleset=Ruleset(), stream=streams.get(COMBAT_STREAM))
assert [goblin.current_hp for goblin in goblins] == [0, 0]  # half of 39 still kills a goblin
assert [event.code for event in events].count("combat.death.died") == 2
assert dragon.breath_uses_today == 1

resolve_energy_drain

resolve_energy_drain(
    attacker: MonsterInstance, target: Creature, *, stream: RngStream, spell_catalog: SpellCatalog | None = None
) -> list[Event]

Drain levels or Hit Dice from the target of an undead creature's hit.

Call this after a wight, wraith, spectre, or vampire hits. resolve_attack deals the hit's damage and leaves the drain to you. This function reads the attacker's energy_drain ability for how many levels to take and how to set a character's experience points. A Character, which has a class, loses levels through drain_levels. A MonsterInstance loses Hit Dice through drain_monster_hd. When the drain kills a character, the drain event includes the ability's text about what the victim becomes.

Parameters:

Name Type Description Default
attacker MonsterInstance

The draining MonsterInstance, whose template has an energy_drain ability.

required
target Creature

The drained Creature, a Character or a MonsterInstance. Its type decides whether levels or Hit Dice come off. The function changes it in place.

required
stream RngStream

The stream the dice for lost hit points come from, usually ADVANCEMENT_STREAM.

required
spell_catalog SpellCatalog | None

The spells a drained character's memorized copies come from, or None for the built-in catalog from load_spells. The function passes it to drain_levels, which looks up the level of each memorized spell in it. A monster target doesn't use it.

None

Returns:

Type Description
list[Event]

The events in order. The first is a LevelDrainedEvent with the code combat.drain.drained. A HitPointsReportedEvent with the target's new hit points comes next. A character then gets a SpellForgottenEvent for each memorized spell it no longer has room for. When the drain kills the target, the first event has the code combat.drain.slain, and only the events of kill follow it.

Raises:

Type Description
ValueError

If the attacker has no energy_drain ability, so it doesn't drain, or a character target has a memorized spell that isn't in spell_catalog. The message for a spell includes its id. The function changes nothing first.

Examples:

from osrlib.core.character import ADVANCEMENT_STREAM
from osrlib.core.combat import resolve_energy_drain
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
wight = spawn_monster(catalog.get("wight"), id="wight-1", stream=spawn)
ogre = spawn_monster(catalog.get("ogre"), id="ogre-1", stream=spawn)

events = resolve_energy_drain(wight, ogre, stream=streams.get(ADVANCEMENT_STREAM))
assert events[0].code == "combat.drain.drained"
assert ogre.hit_dice_count == 3  # the wight's touch takes one Hit Die

resolve_gaze

resolve_gaze(
    gazer: Creature,
    engaged: Sequence[Combatant],
    *,
    stream: RngStream,
    ledger: EffectsLedger,
    clock: GameClock,
    allocator: Any,
    registry: dict[str, Any]
) -> list[Event]

Resolve one round of a petrifying gaze against the creatures in melee with the gazer.

Call this once each round for a basilisk, a medusa, or another monster whose gaze turns creatures to stone, and resolve the monster's attacks separately. You supply the creatures in melee with it, because osrlib.core has no record of where creatures stand. A battle in a GameSession does all of this for you, from each member's BattleDeclaration.gaze_defense.

Each creature in engaged saves versus paralysis. The function skips three kinds of creature: one that's averting its eyes, one with the blind condition, because it can't see the gaze, and one that's already incapacitated. A creature averts its eyes while it has Condition.AVERTED_EYES, which you give it with grant_condition. On a failed save, the function attaches a permanent petrification effect, which gives the petrified condition. A petrified creature isn't dead, and the effect can be ended.

The function doesn't change attack rolls. A creature that fights with its eyes averted takes −4 to hit. A gazer whose entry gives the bonus, like the basilisk, gets +2 to attack it. Apply both through the situational_modifier of each AttackContext. The function doesn't model a mirror either, so leave a creature that watches the gazer in a mirror out of engaged.

Parameters:

Name Type Description Default
gazer Creature

The gazing Creature, usually a MonsterInstance. The function doesn't read it.

required
engaged Sequence[Combatant]

The creatures in melee with the gazer, each a Combatant, which a Character and a MonsterInstance both satisfy.

required
stream RngStream

The stream the saves draw from, usually COMBAT_STREAM. One draw for each creature that saves.

required
ledger EffectsLedger

The EffectsLedger the petrification effect is attached to.

required
clock GameClock

The game clock. The function records its current round as the round the effect was attached.

required
allocator Any

The IdAllocator that assigns the effect ids.

required
registry dict[str, Any]

Your creatures by entity id, so the ledger can find the targets.

required

Returns:

Type Description
list[Event]

For each creature in engaged that saves, in order, its SavingThrowRolledEvent, and on a failed save the events of attaching the petrification.

Examples:

from osrlib.core.clock import GameClock
from osrlib.core.combat import COMBAT_STREAM, resolve_gaze
from osrlib.core.effects import Condition, EffectsLedger, has_condition
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, IdAllocator, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=5)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
basilisk = spawn_monster(catalog.get("basilisk"), id="basilisk-1", stream=spawn)
goblins = [spawn_monster(catalog.get("goblin"), id=f"goblin-{n}", stream=spawn) for n in (1, 2)]

events = resolve_gaze(
    basilisk,
    goblins,
    stream=streams.get(COMBAT_STREAM),
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={goblin.id: goblin for goblin in goblins},
)
assert [event.code for event in events][:2] == ["combat.save.passed", "combat.save.failed"]
assert [has_condition(goblin, Condition.PETRIFIED) for goblin in goblins] == [False, True]

resolve_splash_attack

resolve_splash_attack(
    attacker: Combatant,
    defender: Combatant,
    attack: GearTemplate,
    *,
    context: AttackContext,
    ruleset: Ruleset,
    stream: RngStream,
    ledger: EffectsLedger,
    clock: GameClock,
    allocator: Any,
    registry: dict[str, Any]
) -> AttackResult

Resolve a thrown flask of holy water or oil: the attack, its first damage, and its second.

Use this instead of resolve_attack for holy water and oil, because they damage the target twice: once on the hit, and once more at the next round. This function runs resolve_attack, and on a hit that deals damage it attaches the effect from splash_douse_definition, which deals the second damage when it expires. Attaching it is why this function needs an effects ledger, a clock, an id allocator, and a registry.

Holy water thrown at a living target, and burning oil thrown at a monster that uses fire, hit and do nothing. They aren't rejected, because a rejection costs nothing, and the player could use it to test whether a target is undead or uses fire.

Parameters:

Name Type Description Default
attacker Combatant

The throwing Combatant, which a Character and a MonsterInstance both satisfy.

required
defender Combatant

The target, a Combatant, which a Character and a MonsterInstance both satisfy. The function changes it in place when damage lands.

required
attack GearTemplate

The holy water or oil flask, as a GearTemplate from load_equipment. It must be a splash weapon: its combat stats have the SPLASH quality.

required
context AttackContext

The attack's context. Oil does nothing unless lit is true.

required
ruleset Ruleset

The ruleset in play.

required
stream RngStream

The stream every draw comes from, usually COMBAT_STREAM.

required
ledger EffectsLedger

The EffectsLedger to attach the second damage to. It lands when you advance this ledger to the next round with EffectsLedger.advance.

required
clock GameClock

The game clock. Its current round sets when the second damage lands.

required
allocator Any

The IdAllocator that assigns the effect's id.

required
registry dict[str, Any]

Your creatures by entity id, so the ledger can find the target again.

required

Returns:

Type Description
AttackResult

The attack's outcome. When the second damage was attached, the last event is its EffectAttachedEvent.

Raises:

Type Description
ValueError

If attack isn't a splash weapon, like a torch or a sword. Resolve those with resolve_attack. The function raises before the attack roll, so the stream, the defender, and the ledger don't change.

Examples:

from osrlib.core.clock import GameClock
from osrlib.core.combat import COMBAT_STREAM, AttackContext, resolve_splash_attack
from osrlib.core.effects import EffectsLedger
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, IdAllocator, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

streams = RngStreams(master_seed=5)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
ogre = spawn_monster(catalog.get("ogre"), id="ogre-1", stream=spawn)

result = resolve_splash_attack(
    goblin,
    ogre,
    load_equipment().get("oil_flask"),
    context=AttackContext(lit=True, distance_feet=10),
    ruleset=Ruleset(),
    stream=streams.get(COMBAT_STREAM),
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={"goblin-1": goblin, "ogre-1": ogre},
)
assert result.attack_roll.hit
assert result.damage == 2
assert ogre.current_hp == 15  # down from 17
assert result.events[-1].code == "effects.effect.attached"  # the douse, due next round

roll_initiative

roll_initiative(participants: Sequence[Participant], *, ruleset: Ruleset, stream: RngStream) -> InitiativeResult

Roll initiative for one combat round, by side or, under individual_initiative, by combatant.

Call this at the start of each combat round, then let the combatants act in the order it returns. Build one Participant for each combatant, and get each one's modifier from participant_modifier. The function reads nothing from your creatures and changes nothing. It works only from the participants you pass.

Under side initiative, the default, each side rolls 1d6 and everyone on the side acts on that roll. Under the individual_initiative ruleset flag, each participant rolls 1d6 and adds its modifier.

The function re-rolls every tie. The tabletop rules let the referee re-roll a tie or resolve the tied actions at the same time, and osrlib re-rolls because acting at the same time would need a different combat model. Every side or participant in a tie rolls again, in the order you passed them, until no two totals are the same. A slow participant acts after every participant that isn't slow. Among themselves, slow participants act in initiative order. Participants with the same rank act in the order you passed them.

Parameters:

Name Type Description Default
participants Sequence[Participant]

One for each combatant, each with a different key. Combatants with the same rank act in this order.

required
ruleset Ruleset

The ruleset in play. Its individual_initiative flag picks the mode.

required
stream RngStream

The stream the d6s come from, usually COMBAT_STREAM. One draw for each side, or for each participant under individual initiative, and one more for each re-roll of a tie.

required

Returns:

Type Description
InitiativeResult

Every roll, re-rolls included, and the acting order of every participant.

Raises:

Type Description
ValueError

If two participants have the same key, under either kind of initiative. The function raises before it draws.

Examples:

from osrlib.core.combat import COMBAT_STREAM, Participant, roll_initiative
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset

combat = RngStreams(master_seed=3).get(COMBAT_STREAM)
result = roll_initiative(
    [
        Participant(key="hild", side="party"),
        Participant(key="brand", side="party", slow=True),  # a two-handed sword
        Participant(key="goblin-1", side="goblins"),
    ],
    ruleset=Ruleset(),
    stream=combat,
)
assert result.mode == "side"
assert result.order == ("hild", "goblin-1", "brand")  # the slow actor goes last
assert [(entry.key, entry.total) for entry in result.entries] == [("party", 5), ("goblins", 3)]

roll_reaction

roll_reaction(*, modifier: int = 0, stream: RngStream) -> ReactionRollResult

Roll how monsters react to the party: 2d6 plus a modifier, read on the reaction table.

Roll this when the party meets monsters that aren't already fighting, to learn whether they attack, wait, or talk. The roll changes nothing, and you decide how the monsters act on it. In a session, the encounter procedure rolls it for you, and a hostile result can lead to start_battle.

You supply the modifier, from the npc_reaction_modifier of the character who speaks to the monsters, because the tabletop rules apply it only when one character speaks. The function reads a total outside 2 to 12 as the nearest end of the table, and doesn't treat it as an error.

Parameters:

Name Type Description Default
modifier int

The speaking character's CHA modifier to reactions, when a character speaks.

0
stream RngStream

The stream the 2d6 comes from. A session draws reaction rolls from ENCOUNTER_STREAM, not the combat stream, because they belong to the encounter, not the battle. Two draws.

required

Returns:

Type Description
ReactionRollResult

The outcome. Its ReactionRolledEvent is visible to the referee only, because players learn a monster's mood from what it does.

Examples:

from osrlib.core.combat import roll_reaction
from osrlib.core.rng import RngStreams
from osrlib.crawl.session import ENCOUNTER_STREAM

encounter = RngStreams(master_seed=3).get(ENCOUNTER_STREAM)

met = roll_reaction(stream=encounter)
assert met.roll == 6
assert met.result == "uncertain"

spoken_to = roll_reaction(modifier=2, stream=encounter)
assert (spoken_to.roll, spoken_to.modifier, spoken_to.total) == (3, 2, 5)
assert spoken_to.result == "hostile"  # a 5 is still a bad start

saving_throw

saving_throw(
    target: Combatant,
    category: SaveCategory,
    *,
    modifier: int = 0,
    magical: bool = False,
    element: str | None = None,
    source: Creature | None = None,
    stream: RngStream
) -> SaveResult

Roll a saving throw: 1d20 plus modifiers, which passes at or above the target's number for the category.

Call this whenever something forces a save, then act on passed yourself: the function reports the outcome and changes nothing. Pick the category from SaveCategory. resolve_breath and resolve_gaze already roll the saves they need, so you need this function for spells, traps, poisons, and saves of your own.

The roll adds the target's bonuses for you:

  • A character's WIS modifier, when magical is true and the category isn't breath. The rules say the WIS bonus "does not normally include saves against breath attacks".
  • Bonuses from spells on the target. Some apply to every save. Some apply only against an element, like resist fire against fire. Some apply only against a source of another alignment, like protection from evil. Spell bonuses don't add up: only the largest bonus and the largest penalty count.
  • Bonuses from magic items the target has equipped, like a ring of protection. They add on top of the spell bonuses.

Pass any other adjustment, like a referee's ruling, in modifier. A monster whose defenses give it an automatic save against a magical effect of an element, as a red dragon has against magical fire, passes without a roll and without a draw.

Parameters:

Name Type Description Default
target Combatant

The saving Combatant, which a Character and a MonsterInstance both satisfy.

required
category SaveCategory

The saving throw category.

required
modifier int

Your adjustment, added to the target's bonuses.

0
magical bool

Whether the effect is magical. It turns on the WIS modifier, and a monster's automatic save against an element needs it.

False
element str | None

The effect's element, like fire, or None. The function reads it for element bonuses and automatic saves.

None
source Creature | None

The Creature whose attack or ability forced the save, a Character or a MonsterInstance. The function reads it only for bonuses against another alignment.

None
stream RngStream

The stream the d20 comes from, usually COMBAT_STREAM. One draw, or none for an automatic save.

required

Returns:

Type Description
SaveResult

The outcome. Read passed to decide the consequence. roll is None on an automatic save. events contains the SavingThrowRolledEvent, with the code combat.save.passed, combat.save.failed, or combat.save.auto.

Examples:

from osrlib.core.combat import COMBAT_STREAM, SaveCategory, saving_throw
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)

result = saving_throw(goblin, SaveCategory.DEATH, stream=streams.get(COMBAT_STREAM))
assert (result.roll, result.required) == (20, 14)
assert result.passed
assert [event.code for event in result.events] == ["combat.save.passed"]

select_targets

select_targets(
    mode: TargetingMode,
    candidates: Sequence[Creature],
    *,
    stream: RngStream,
    count: int | None = None,
    count_dice: str | None = None,
    hd_budget: int | None = None
) -> tuple[list[Creature], list[Event]]

Choose which of the candidates you list a spell or other area effect reaches.

cast_spell calls this for a spell that targets up to a number of creatures, or a budget of Hit Dice. Call it yourself to apply the same rules to an effect of your own. You supply the candidates, because osrlib.core has no record of where creatures stand: who's in range or in the blast is your judgment. In a session, osrlib.crawl.battle supplies them from the distances it tracks. Pass the selected targets to whatever resolves the effect, like saving_throw or deal_damage.

Each TargetingMode chooses its targets this way:

  • self and single take the first candidate.
  • up_to_n takes the first N candidates in your order. N is the fixed count, or a roll of count_dice, like the 1d4 of hold person.
  • area and gaze take every candidate.
  • hd_budget takes candidates weakest first, by effective_hd, with equal ones in your order, until the budget runs out. It skips a candidate with more Hit Dice than the budget has left, and goes on down the list. That's how sleep works.

Parameters:

Name Type Description Default
mode TargetingMode

The targeting mode.

required
candidates Sequence[Creature]

The creatures that could be targeted, in the order you want them chosen when the mode or a tie leaves a choice. Each is a Creature, which a Character and a MonsterInstance both satisfy.

required
stream RngStream

The stream a rolled count draws from, usually COMBAT_STREAM. Only count_dice draws.

required
count int | None

The fixed N for up_to_n, 1 or more.

None
count_dice str | None

The dice expression, like 1d4, for a rolled N in up_to_n. When you pass both, the function uses count. The up_to_n mode requires one of the two.

None
hd_budget int | None

The Hit Dice budget for hd_budget, 1 or more, which that mode requires.

None

Returns:

Type Description
tuple[list[Creature], list[Event]]

The selected targets, and a list with one TargetsSelectedEvent, which is visible to the referee only. The targets are in the order they were chosen, which for hd_budget is weakest first.

Raises:

Type Description
ValueError

If the mode is up_to_n and neither count nor count_dice is set, or count is less than 1. Also if the mode is hd_budget and hd_budget is None or less than 1, or if mode isn't one of the targeting modes. The function raises before it draws.

Examples:

from osrlib.core.combat import COMBAT_STREAM, TargetingMode, select_targets
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

streams = RngStreams(master_seed=3)
spawn = streams.get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
ogre = spawn_monster(catalog.get("ogre"), id="ogre-1", stream=spawn)
goblins = [spawn_monster(catalog.get("goblin"), id=f"goblin-{n}", stream=spawn) for n in (1, 2, 3)]
combat = streams.get(COMBAT_STREAM)

# Four Hit Dice of sleep: three 1 HD goblins first, then nothing left for the 4 HD ogre.
selected, events = select_targets(TargetingMode.HD_BUDGET, [ogre, *goblins], stream=combat, hd_budget=4)
assert [target.id for target in selected] == ["goblin-1", "goblin-2", "goblin-3"]
assert events[0].code == "combat.targeting.selected"

selected, _ = select_targets(TargetingMode.UP_TO_N, goblins, stream=combat, count=2)
assert [target.id for target in selected] == ["goblin-1", "goblin-2"]

splash_douse_definition

splash_douse_definition(attack: Attack, source: DamageSource) -> EffectDefinition

Build the effect that deals a splash weapon's second round of damage.

The rules say oil and holy water deal their damage "for two rounds". osrlib reads that as two hits of damage: the first when the flask hits, and the second, with the same dice, when this one-round effect expires. osrlib calls this effect the douse. resolve_splash_attack builds and attaches it for you on a hit that deals damage. Call this function yourself only to attach the douse through your own EffectsLedger. Build the source with damage_source_for from the same attack and context, so the second hit has the same keys and element as the first.

Parameters:

Name Type Description Default
attack Attack

The splash item. The ledger rolls its combat stats' damage dice again for the second hit.

required
source DamageSource

The damage source of the first hit. The second hit has the same keys and element.

required

Returns:

Type Description
EffectDefinition

A one-round EffectDefinition whose expiry deals the second hit. Attach it with EffectsLedger.attach, and the second hit lands when EffectsLedger.advance reaches the next round.

Raises:

Type Description
ValueError

If the attack has no combat stats, so there are no dice for the second hit.

Examples:

from osrlib.core.combat import AttackContext, damage_source_for, splash_douse_definition
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_equipment, load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
goblin = spawn_monster(load_monsters().get("goblin"), id="goblin-1", stream=spawn)

oil = load_equipment().get("oil_flask")
context = AttackContext(lit=True)
definition = splash_douse_definition(oil, damage_source_for(goblin, oil, context))
assert definition.kind == "splash_douse"
assert definition.duration_amount == 1
assert definition.params == {"dice": "1d8", "keys": (), "element": "fire"}

validate_attack

validate_attack(
    attacker: Creature, defender: Creature, attack: Attack, context: AttackContext, *, ruleset: Ruleset
) -> list[Rejection]

Check whether an attack is allowed, without rolling anything or changing anything.

Call this before resolve_attack to tell the player why an attack can't happen instead of resolving it. resolve_attack doesn't call it for you, and resolves whatever you pass it. An empty list means the attack may go ahead.

The rejections, by Rejection code:

  • combat.attack.attacker_incapacitated: the attacker is dead, turned to stone, paralysed, asleep, or weakened. The condition param is the condition.
  • combat.attack.attacker_blind: the attacker is blind.
  • combat.attack.out_of_range: a missile is aimed past its long range.
  • combat.attack.reload: under the weapon_reload ruleset flag, a reload-quality weapon, like a crossbow, fired in the previous round too.
  • combat.attack.out_of_reach: a melee attack at a distance beyond MELEE_REACH_FEET.

An attacker who is incapacitated or blind gets that one rejection, and the other checks don't run. The rejection code reference lists every code and its params.

Parameters:

Name Type Description Default
attacker Creature

The attacking Creature, which a Character and a MonsterInstance both satisfy. The function reads only its conditions.

required
defender Creature

The defending Creature, a Character or a MonsterInstance. The function doesn't read it.

required
attack Attack

The Attack, or None for unarmed.

required
context AttackContext

The attack's context. The function reads only distance_feet and fired_last_round.

required
ruleset Ruleset

The ruleset in play. The function reads only weapon_reload.

required

Returns:

Type Description
list[Rejection]

The reasons the attack isn't allowed, as Rejection values. Each has a code and the params a message needs. The list is empty when the attack may go ahead.

Examples:

from osrlib.core.combat import AttackContext, validate_attack
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment, load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)
orc = spawn_monster(catalog.get("orc"), id="orc-1", stream=spawn)
sword = load_equipment().get("sword")
rules = Ruleset()

assert validate_attack(goblin, orc, sword, AttackContext(distance_feet=5), ruleset=rules) == []

far = validate_attack(goblin, orc, sword, AttackContext(distance_feet=30), ruleset=rules)
assert far[0].code == "combat.attack.out_of_reach"
assert far[0].params == {"attacker": "goblin-1", "distance_feet": 30}

validate_breath

validate_breath(monster: MonsterInstance) -> list[Rejection]

Check whether a monster may use its breath weapon, without rolling anything or changing anything.

Call this before resolve_breath, which raises an error, instead of returning a rejection, when the monster can't breathe. An empty list means the monster may breathe.

The rejections, by Rejection code:

  • combat.breath.no_breath_weapon: the monster has no breath weapon.
  • combat.breath.exhausted: the monster has used its breath weapon as many times today as its daily limit allows, which is three for a dragon. The uses_per_day param has the limit.

A breath weapon with no daily limit, like a hellhound's, is never exhausted. How often such a monster breathes is up to whatever chooses its actions.

Parameters:

Name Type Description Default
monster MonsterInstance

The breathing MonsterInstance. The function checks its breath_uses_today against the limit.

required

Returns:

Type Description
list[Rejection]

The reasons the monster can't breathe, as Rejection values. The list is empty when the monster may breathe.

Examples:

from osrlib.core.combat import validate_breath
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.data import load_monsters

spawn = RngStreams(master_seed=3).get(MONSTER_SPAWN_STREAM)
catalog = load_monsters()
dragon = spawn_monster(catalog.get("white_dragon"), id="dragon-1", stream=spawn)
goblin = spawn_monster(catalog.get("goblin"), id="goblin-1", stream=spawn)

assert validate_breath(dragon) == []
assert validate_breath(goblin)[0].code == "combat.breath.no_breath_weapon"

dragon.breath_uses_today = 3
assert validate_breath(dragon)[0].code == "combat.breath.exhausted"