Skip to content

osrlib.core.spells

Spell memorization, casting, spell resolution, and turning undead.

The functions in this module run the magic rules: preparing spells for the day, casting them, resolving what they do, and turning undead. The functions that act on a caster change the caster and the effects ledger in place and return events, and the functions named validate_ change nothing. Everything here runs without a game session, and every random draw comes from a seeded RNG stream you pass in.

The module uses these terms:

  • A caster's spell slots are how many spells of each spell level they can prepare. They are the spell_slots of the progression row for the caster's level in their ClassDefinition.
  • A memorized copy is one prepared spell, a MemorizedSpell. Casting a spell spends one copy.
  • A mode is one castable usage of a spell, a SpellMode. A spell page that prints two numbered usages has two modes.
  • The effects ledger is the EffectsLedger that contains what a cast leaves running, like a condition or a timed bonus. Its advance method counts each effect down and releases it when it ends.

The members, in the order you use them:

A template's fields contain the rest as models you read: one SpellMode per mode, each with a TargetingSpec, a SaveSpec, and a SpellEffect, and the ReversedForm, DurationSpec, and RangeSpec. EFFECT_KINDS lists what an effect can do, and MAGIC_STREAM is the name of the RNG stream for spell draws. Every model in this module is frozen: assigning to one of its fields raises pydantic.ValidationError.

In a game session, you execute commands instead of calling these functions, and the crawl layer, the osrlib.crawl package, calls them after the session's checks pass. PrepareSpells requires a night's sleep before preparation, UseItem lets a character read a scroll only when there's light to read by, and LearnSpell, CastSpell, and TurnUndead check the session's mode. Call this module's functions directly when you run the rules yourself.

The OSE SRD's spell pages compile into the catalog of SpellTemplate models. A template has the page's printed duration, range, and text, and one mode per castable usage. Each mode has its targeting, its saving throw, and, when osrlib resolves the mode itself, the effect that casting runs. A mode osrlib doesn't resolve is marked manual=True and has the SRD's text. Casting a manual mode still spends the copy and returns the cast event, and you decide what happens.

A reversible spell's reverse, like cause light wounds for cure light wounds, isn't a separate catalog entry. It's the template's reversed_form, a ReversedForm. A spell the SRD prints twice, once on a cleric page and once on a magic-user page with different rules, is two entries: the cleric one has the id suffix _c and the magic-user one _mu, like light_c and light_mu.

Casters are Caster values, which a Character satisfies and a monster doesn't. Targets are Creature values, which characters and MonsterInstance objects satisfy, or location strings for effects you attach to places rather than to creatures.

Every random draw made while a spell resolves comes from the MAGIC_STREAM stream: targeting dice, damage dice, touch attack rolls, the targets' saving throws, dispel magic's survival rolls, and both turning rolls. Spell results and combat draws therefore replay independently of each other. Draws made for an attached effect, like a duration rolled as it attaches or a charmed creature's later saving throws to break free, come from the EFFECTS_STREAM stream.

Typical usage:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import GameClock
from osrlib.core.effects import EFFECTS_STREAM, EffectsLedger
from osrlib.core.monsters import IdAllocator
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import MAGIC_STREAM, MemorizedSpell, cast_spell, caster_profile, memorize_spells
from osrlib.data import load_classes, load_spells

rules = Ruleset()
streams = RngStreams(master_seed=7)
catalog = load_spells()
definition = load_classes().get("cleric")

aldis = create_character(
    name="Aldis",
    class_id="cleric",
    alignment=Alignment.LAWFUL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character
aldis.id = "pc-1"
aldis.level = 2  # a 2nd-level cleric has one first-level slot

# Prepare the day's list, then cast the spell to heal the caster.
prepared = memorize_spells(aldis, definition, catalog, [MemorizedSpell(spell_id="cure_light_wounds")])
assert prepared.accepted
aldis.current_hp = 1
result = cast_spell(
    aldis,
    catalog.get("cure_light_wounds"),
    "heal",
    profile=caster_profile(definition),
    targets=[aldis],
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={"pc-1": aldis},
    ruleset=rules,
    stream=streams.get(MAGIC_STREAM),
    effects_stream=streams.get(EFFECTS_STREAM),
)
assert result.affected_ids == ("pc-1",)
assert aldis.current_hp == aldis.max_hp  # healing never exceeds the normal maximum
assert aldis.memorized_spells == ()  # the cast spent the copy

EFFECT_KINDS module-attribute

EFFECT_KINDS = frozenset(
    {"damage", "heal", "cure", "condition", "modifiers", "kill", "restore_life", "dispel", "attach_only"}
)

The effect kinds osrlib can resolve when a spell is cast.

SpellEffect.kind must be one of these, so a spell you write yourself has to use one of these behaviors, or have its mode marked manual and left to you. Each kind is a branch of osrlib's resolution code, so a new kind needs a change to osrlib, not only new data.

  • damage: casting rolls damage dice against each target.
  • heal: casting rolls healing dice for each target.
  • cure: casting releases the effects that put named conditions on a target, or effects of named kinds.
  • condition: casting attaches an effect that puts a condition on each target.
  • modifiers: casting attaches an effect that gives each target bonuses or penalties.
  • attach_only: casting attaches an effect with no condition, as for light, fly, and mirror image.
  • kill: casting kills each target, as for death spell and disintegrate.
  • restore_life: casting brings a dead character back, as for raise dead.
  • dispel: casting releases magical effects, as for dispel magic.

MAGIC_STREAM module-attribute

MAGIC_STREAM = StreamName.MAGIC

The name of the RNG stream that every draw made while a spell resolves comes from.

Pass streams.get(MAGIC_STREAM) as the stream argument of cast_spell, cast_from_scroll, and turn_undead, where streams is an RngStreams. The draws on it are targeting dice, damage dice, touch attack rolls, the targets' saving throws, dispel magic's survival rolls, and both turning rolls.

Because magic has a separate stream, a replay reproduces a spell result even after the combat draws around it have changed, and the reverse. Draws made for an attached effect come from EFFECTS_STREAM instead, so pass that stream as effects_stream rather than this one.

CastContext

Bases: BaseModel

Facts about a cast's situation that osrlib can't work out, which you state for the rules to use.

Construct one and pass it to validate_cast, cast_spell, validate_scroll_cast, or cast_from_scroll. Every field is optional. The default context sets none of them, which is right when none of these facts applies.

At the table, a referee answers these questions, and osrlib has nothing to answer them from. It has no map, so it can't work out how far away the target is. It has no model of restraints, so it can't tell that the caster is tied up. It doesn't record the cause of death, so it can't tell that the target died of poison.

A rule whose field you leave unset doesn't apply. Range goes unchecked if you give no distance, and raise dead raises nobody if you give no number of days since death.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import CastContext, MemorizedSpell, caster_profile, memorize_spells, validate_cast
from osrlib.data import load_classes, load_spells

catalog = load_spells()
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=RngStreams(master_seed=5).get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["sleep"],
).character
memorize_spells(zelia, definition, catalog, [MemorizedSpell(spell_id="sleep")])
profile = caster_profile(definition)
sleep = catalog.get("sleep")

# Her captors have gagged her, so she can't speak the words.
refused = validate_cast(zelia, sleep, "hd_budget", profile=profile, context=CastContext(gagged=True))
print([(rejection.code, rejection.params["restraint"]) for rejection in refused])
# [('magic.cast.caster_restrained', 'gagged')]

in_combat class-attribute instance-attribute

in_combat: bool = False

True when the cast happens in a fight.

In combat, a touch spell like cause light wounds needs a melee attack roll and can miss. Outside combat, the caster touches the target without a roll.

distance_feet class-attribute instance-attribute

distance_feet: int | None = None

How far the target is from the caster, in feet.

Setting it turns on the range check in validation. Validation rejects the cast when the distance is more than the spell's RangeSpec reaches at the caster level in use. A touch spell reaches 5', so a touch spell at more than 5' is rejected too. Leave it unset, and no range check happens.

bound class-attribute instance-attribute

bound: bool = False

True when the caster is tied or held so that they can't gesture. Validation rejects the cast.

gagged class-attribute instance-attribute

gagged: bool = False

True when the caster can't speak. Validation rejects the cast.

rounds_since_death class-attribute instance-attribute

rounds_since_death: int | None = None

How many rounds ago the target died, for neutralize poison.

That spell revives a character killed by poison within the last 10 rounds. When you set this field, you state that poison was the cause, because osrlib doesn't record the cause of death. Leave it unset for a death by any other cause.

days_since_death class-attribute instance-attribute

days_since_death: int | None = None

How many days ago the target died, for raise dead.

That spell can raise a character dead up to 4 days for each caster level above 7th. Leave it unset, and nobody is raised.

strength_tiers class-attribute instance-attribute

strength_tiers: dict[str, str] = {}

Entity ids mapped to "augmented" or "giant", for web.

A stronger creature breaks free of a web sooner. A creature you don't list breaks free at normal strength. You state it here because web doesn't check a creature's items or effects for strength, not even a girdle of giant strength.

CastResult

Bases: BaseModel

What a cast did: which copy was spent, who it reached, and everything that happened.

cast_spell and cast_from_scroll return one. A result always describes a cast that happened, because an illegal cast raises instead. By the time you have a result, the copy is spent, and the targets, the caster, and the ledger have changed. Publish events to whatever shows the game, and read manual, no_effect, and affected_ids to tell the player what happened.

Two outcomes need more than the events. manual means osrlib spent the copy and resolved nothing: prose has the SRD text, and you decide what happened. no_effect means the cast resolved and reached nobody, because no candidate was eligible, every target saved or was immune, or a touch attack missed. In both cases the copy is gone. osrlib refunds nothing once a cast resolves, because a refund would tell the player something they had no way to know, like the fact that the creature they aimed at was immune.

spell_id instance-attribute

spell_id: str

The id of the spell that was cast, which SpellCatalog.get takes.

mode instance-attribute

mode: str

The SpellMode.key of the mode that was cast.

reversed class-attribute instance-attribute

reversed: bool = False

True when the reversed form was cast.

manual class-attribute instance-attribute

manual: bool = False

True when the mode is one osrlib doesn't resolve. Read prose, and decide what happens.

no_effect class-attribute instance-attribute

no_effect: bool = False

True when the cast resolved and reached nobody. The copy is still spent.

prose class-attribute instance-attribute

prose: str = ''

The SRD text of the mode that was cast, to show a player.

affected_ids class-attribute instance-attribute

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

The entity id of each creature the cast reached, in the order it was reached, each once.

For a cast at a place, it has the location string you passed as a target instead. Empty when no_effect or manual is set.

events class-attribute instance-attribute

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

Everything that happened, in order.

The SpellCastEvent comes first. Its target_ids are the candidates you passed, not only the ones reached. Then come the events for each saving throw, each wound, and each effect attached or released. Publish these, and keep them for a replay.

CasterProfile

Bases: BaseModel

What kind of caster a class is, and which spell list it draws on.

Get one from caster_profile, which reads it from a class definition. Pass it as the profile argument of validate_cast and cast_spell.

kind instance-attribute

kind: Literal['divine', 'arcane']

"divine" for a class that prays for its spells, "arcane" for one that studies them from a book.

The two kinds differ in three ways. Only an arcane caster has a spell book, which add_spell_to_book adds to. Only an arcane caster chooses a spell's reversed form when memorizing it. Only a divine caster can cast any memorized copy in either form.

spell_list instance-attribute

spell_list: str

The id of the spell list the class uses, like "cleric" or "magic_user".

It has to match SpellTemplate.spell_list for the class to memorize or learn a spell. Pass it to SpellCatalog.by_list for the spells the class can choose from.

DurationSpec

Bases: BaseModel

How long a spell lasts, parsed out of the printed duration line.

Read one from SpellTemplate.duration_spec, or from ReversedForm.duration_spec when the reverse lasts a different length. Casting reads it for you and turns it into the duration of the effect it attaches to the ledger. You need this model when you show a spell, sort or filter spells by how long they last, or write a spell of your own.

The printed line is the template's duration, and that's what you show a player. A printed duration that has no structure osrlib can read, like "Special", is stored here as kind="special" with no other field set.

Constructing one raises pydantic.ValidationError when dice isn't a valid dice expression, or when a fixed duration has no unit, or has no amount, dice, or per_level.

Examples:

from osrlib.core.clock import TimeUnit
from osrlib.data import load_spells

catalog = load_spells()
light = catalog.get("light_mu")
assert light.duration == "6 turns +1 per level"  # the printed line
spec = light.duration_spec
assert (spec.kind, spec.unit, spec.amount, spec.per_level) == ("fixed", TimeUnit.TURN, 6, 1)
# So a 3rd-level caster's light lasts 6 + 1 * 3 turns.
assert catalog.get("cure_light_wounds").duration_spec.kind == "instant"

kind instance-attribute

kind: Literal['instant', 'permanent', 'concentration', 'fixed', 'special']

Which kind of duration this is.

  • instant: the spell resolves and is over.
  • permanent: the effect never ends on its own.
  • concentration: the effect lasts while the caster concentrates. Casting attaches it with no end, and you release it from the ledger when the caster stops.
  • fixed: a length counted in unit.
  • special: the printed line has no structure osrlib can read. Casting attaches the effect with no end, and you release it when the printed line describes.

unit class-attribute instance-attribute

unit: TimeUnit | None = None

The time unit a fixed duration counts in: rounds, turns, or days. None on every other kind.

See TimeUnit.

amount class-attribute instance-attribute

amount: int | None = None

How many unit a fixed duration lasts, before the per-level bonus.

None when the length is rolled with dice. When amount and dice are both None, the length is per_level times the caster's level.

dice class-attribute instance-attribute

dice: str | None = None

A dice expression for a rolled length, in place of amount.

Sleep lasts "4d4" turns. osrlib rolls the dice on the effects stream when the effect attaches.

per_level class-attribute instance-attribute

per_level: int = 0

How many extra unit the duration lasts per caster level.

Casting adds it to amount, or to the modifier of dice. Light prints 6 turns +1 per level, so amount is 6 and per_level is 1, and a 3rd-level caster's light lasts 9 turns.

concentration_cap_unit class-attribute instance-attribute

concentration_cap_unit: TimeUnit | None = None

The unit of the longest a concentration duration can last, when the page prints a limit.

Insect plague prints Concentration (up to 1 day), so this is days and concentration_cap_amount is 1. None when the page prints no limit. Casting doesn't apply the limit.

concentration_cap_amount class-attribute instance-attribute

concentration_cap_amount: int | None = None

How many concentration_cap_unit a concentration duration can last. None when the page prints no limit.

MemorizationResult

Bases: BaseModel

What came of a call to memorize_spells.

One of the two fields is always empty. When the preparation was legal, the caster's memorized list was replaced, and events reports it. When it wasn't, rejections gives the reasons, and nothing changed. Check accepted rather than testing either tuple yourself.

rejections class-attribute instance-attribute

rejections: tuple[Rejection, ...] = ()

Why the preparation was refused, as Rejection models.

Each has a code and params you can turn into a message in your own words. Each problem found in the list has a rejection, not only the first, so a player can fix the whole list at once. Empty on success.

events class-attribute instance-attribute

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

The one SpellsMemorizedEvent, which lists what was prepared.

Empty on a rejection.

accepted property

accepted: bool

Whether the caster's memorized list was replaced.

False means nothing changed, and rejections gives the reasons.

MemorizedSpell

Bases: BaseModel

One spell a caster has ready to cast: which spell, and in which form.

Construct one for each slot you want filled, and pass them to memorize_spells or to the PrepareSpells command. Read them back from a character's memorized_spells, in the order they were prepared. Which copy goes depends on the order: casting spends the first copy that matches, and forget_excess_memorized, which drain_levels calls, removes the last ones first.

A copy has only a spell id and a form. What the spell can do comes from the template you get with SpellCatalog.get.

Examples:

from osrlib.core.spells import MemorizedSpell

prepared = [MemorizedSpell(spell_id="magic_missile"), MemorizedSpell(spell_id="light_mu", reversed=True)]
assert prepared[1].reversed  # this copy casts *darkness*, not *light*

spell_id class-attribute instance-attribute

spell_id: str = Field(min_length=1)

The spell's id, like "magic_missile".

For the built-in ids, iterate load_spells().spells or see the spell id index.

reversed class-attribute instance-attribute

reversed: bool = False

True when this copy is prepared as the spell's reversed form.

Only an arcane caster sets it, because in the SRD an arcane caster chooses the form when the spell is memorized. A divine caster memorizes the normal form and chooses the form when casting, so a divine caster's copies are always False, and memorize_spells rejects a copy marked True.

RangeSpec

Bases: BaseModel

How far a spell reaches, parsed out of the printed range line.

Read one from SpellTemplate.range_spec. validate_cast reads it for you, but only when you pass the distance to the target in CastContext.distance_feet. osrlib has no map, so with no distance there's no range check. Read this model yourself when you draw a range indicator, filter spells by reach, or decide which targets to offer.

The printed line is the template's range, and that's what you show a player. A printed range with no structure osrlib can read, like "Appears in the caster’s presence", is stored as kind="special" with no distance.

Examples:

from osrlib.data import load_spells

catalog = load_spells()
assert catalog.get("fire_ball").range == "240’"
fire_ball = catalog.get("fire_ball").range_spec
assert (fire_ball.kind, fire_ball.feet) == ("feet", 240)
assert catalog.get("cure_light_wounds").range_spec.kind == "touch"

kind instance-attribute

kind: Literal['caster', 'touch', 'feet', 'yards', 'per_level', 'special']

Which kind of range this is.

  • caster: the spell affects only the caster.
  • touch: the spell affects a creature the caster touches, which can be the caster. It reaches 5', as far as a melee attack (MELEE_REACH_FEET), so validate_cast refuses a touch spell at a distance_feet beyond that with magic.cast.out_of_range.
  • feet and yards: a fixed distance, in feet.
  • per_level: a distance that grows with caster level.
  • special: the printed line has no structure osrlib can read.

feet class-attribute instance-attribute

feet: int | None = None

The distance in feet, for the feet, yards, and per_level kinds. None on the other kinds.

Yards are converted, so a range printed as 240 yards is 720 here. On a per_level range this is the distance before the per-level bonus, and it is None when the printed range is only a distance per level, like 10’ per level.

per_level_feet class-attribute instance-attribute

per_level_feet: int | None = None

Extra feet of reach per caster level on a per_level range. None on the other kinds.

A range printed 60’ +10’ per level is feet 60 and per_level_feet 10, so a 5th-level caster reaches 110 feet.

ReversedForm

Bases: BaseModel

The reverse of a reversible spell, stored on the spell's entry.

Cure light wounds reverses into cause light wounds, and light into darkness. The reverse is never a separate catalog entry. Read it from SpellTemplate.reversed_form, which is None on a spell that doesn't reverse. To cast it, pass reversed=True to cast_spell with a mode key from this form's modes. The reverse's keys can differ from the normal form's: cure light wounds has heal and cure_paralysis, and its reverse has harm.

When the form is chosen depends on the kind of caster. An arcane caster chooses normal or reversed when memorizing, and the choice is the MemorizedSpell's reversed field. A divine caster memorizes the normal form and chooses when casting, by speaking the words backwards, so any of their memorized copies can be cast either way.

Examples:

from osrlib.data import load_spells

cure = load_spells().get("cure_light_wounds")
assert cure.reversed_form.name == "Cause Light Wounds"
assert [mode.key for mode in cure.modes] == ["heal", "cure_paralysis"]
assert [mode.key for mode in cure.reversed_form.modes] == ["harm"]  # different keys
assert load_spells().get("magic_missile").reversed_form is None  # not reversible

name class-attribute instance-attribute

name: str = Field(min_length=1)

The reverse's name, as the SRD prints it, like "Cause Light Wounds".

Show this rather than the template's name when a cast is reversed.

prose class-attribute instance-attribute

prose: str = ''

The SRD text for the reverse.

modes class-attribute instance-attribute

modes: tuple[SpellMode, ...] = Field(min_length=1)

One SpellMode per castable usage of the reverse, at least one, each with a different key.

duration class-attribute instance-attribute

duration: str | None = None

The reverse's printed duration, when the page prints a different one for it.

None means the normal form's duration applies.

duration_spec class-attribute instance-attribute

duration_spec: DurationSpec | None = None

The structured form of duration, as a DurationSpec.

None means the reverse lasts as long as the normal form, which is the usual case. A page that prints two durations in one line, like remove curse's Instant / Permanent (curse), gives the second one to the reverse.

SaveSpec

Bases: BaseModel

The saving throw one castable usage of a spell allows its targets, and what passing it does.

Read one from SpellMode.save, which is None when the mode allows no save. Casting rolls each target's save for you on the magic stream, with saving_throw. Read this model to show a player what a target faces before they cast, or to explain why a target came through unharmed.

A spell's save counts as a save against magic, so a character's WIS adjustment applies. A monster with an automatic save against the element of a damage spell, like a red dragon against fire ball, passes without a roll.

Examples:

from osrlib.core.combat import SaveCategory
from osrlib.data import load_spells

catalog = load_spells()
assert catalog.get("magic_missile").mode("missiles").save is None  # no save: it always hits
fire_ball = catalog.get("fire_ball").mode("damage").save
assert (fire_ball.category, fire_ball.on_save) == (SaveCategory.SPELLS, "half")
assert catalog.get("hold_person_mu").mode("individual").save.modifier == -2

category instance-attribute

category: SaveCategory

Which saving throw the target rolls, as a SaveCategory.

modifier class-attribute instance-attribute

modifier: int = 0

The adjustment added to the target's roll. A negative value makes the save harder.

Hold person's single-target mode is −2, and feeblemind is −4.

on_save class-attribute instance-attribute

on_save: Literal['negates', 'half'] = 'negates'

What passing the save does.

negates means the spell does nothing to that target. half means the target still takes half the damage, rounded down.

SpellBookResult

Bases: BaseModel

What came of a call to add_spell_to_book.

One of the two fields is always empty. Either the spell went into the book and events reports it, or it didn't, rejections gives the reason, and the book is unchanged. Check accepted rather than testing either tuple yourself.

rejections class-attribute instance-attribute

rejections: tuple[Rejection, ...] = ()

Why the addition was refused, as Rejection models.

Each has a code and params. There's at most one, because the call stops at the first problem. Empty on success.

events class-attribute instance-attribute

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

The one SpellBookUpdatedEvent for the new spell.

Empty on a rejection.

accepted property

accepted: bool

Whether the spell went into the book.

False means the book is unchanged, and rejections gives the reason.

SpellCatalog

Bases: BaseModel

A set of spell templates, with lookup by id and by class list.

load_spells returns the built-in catalog. It validates the data on the first call and returns the same object on every later call. Every function in this module that needs spell data takes either a catalog or one SpellTemplate from it. To add spells of your own, build a catalog from the built-in spells and yours, and pass it instead.

Use get when you have an id, and by_list when you build a menu of the spells a caster may choose. To find which list a caster's class uses, call caster_profile on their class definition.

Constructing one raises pydantic.ValidationError when two templates have the same id.

Examples:

from osrlib.data import load_spells

catalog = load_spells()
assert catalog.get("sleep").level == 1
assert catalog.spells == tuple(sorted(catalog.spells, key=lambda spell: spell.id))

spells instance-attribute

spells: tuple[SpellTemplate, ...]

Every spell template in the catalog, each with a different id.

The built-in catalog is in id order. A catalog you build is in the order you gave it. Iterate this to search on something the two lookup methods don't cover, like a name or an effect kind.

get

get(spell_id: str) -> SpellTemplate

Return one spell by its id.

A MemorizedSpell, a caster's spell_book, and the events this module returns all refer to spells by id. Call this to turn an id back into the spell's data, then pass the template to cast_spell.

Parameters:

Name Type Description Default
spell_id str

The spell's id, like "fire_ball" or "hold_person_c". Iterate spells for every id in this catalog, or see the spell id index for the built-in ones.

required

Returns:

Type Description
SpellTemplate

Raises:

Type Description
ValueError

If no spell has that id. The message includes the id you passed. An id that osrlib gave you resolves in the catalog it came from, so this error means the id came from somewhere else, like a typo or a save made with a different catalog.

Examples:

from osrlib.data import load_spells

catalog = load_spells()
assert catalog.get("hold_person_c").name == "Hold Person"
try:
    catalog.get("fireball")  # the id is "fire_ball"
except ValueError as error:
    assert str(error) == "unknown spell id 'fireball'"

by_list

by_list(spell_list: str, level: int | None = None) -> tuple[SpellTemplate, ...]

Return the spells a class may draw on, optionally narrowed to one spell level.

This is the menu a caster chooses from: what an arcane caster may add to their spell book with add_spell_to_book, and what a divine caster may prepare with memorize_spells. Pass level to fill one slot, because a caster's slots are counted per spell level.

Get the list id from the spell_list of caster_profile rather than typing it, so your code also works for a class you write with a new spell list.

Parameters:

Name Type Description Default
spell_list str

The list id, like "cleric" or "magic_user". For an id that matches no spell, it returns an empty tuple instead of raising.

required
level int | None

A spell level, 1 to 6, to filter by. None returns the whole list.

None

Returns:

Type Description
tuple[SpellTemplate, ...]

The matching SpellTemplate models in the catalog's order, which for the built-in catalog is id order. Empty when nothing matches.

Examples:

from osrlib.core.spells import caster_profile
from osrlib.data import load_classes, load_spells

catalog = load_spells()
profile = caster_profile(load_classes().get("cleric"))
first_level = catalog.by_list(profile.spell_list, 1)
assert [spell.id for spell in first_level][:3] == [
    "cure_light_wounds",
    "detect_evil_c",
    "detect_magic_c",
]
assert len(catalog.by_list(profile.spell_list)) > len(first_level)
assert catalog.by_list("druid") == ()  # no such list in the built-in catalog

SpellEffect

Bases: BaseModel

What one castable usage of a spell does to its targets.

Read one from SpellMode.effect. Casting runs it for you. You need this model to describe a spell in an interface, to decide whether a spell is worth casting on a given target, or to write a spell of your own.

A mode marked manual in the built-in catalog has no effect: its effect is None, and casting it spends the copy, returns the cast event, and leaves the outcome to you. Every other mode has an effect.

Constructing one raises pydantic.ValidationError when kind isn't one of EFFECT_KINDS.

Examples:

from osrlib.core.effects import Condition
from osrlib.data import load_spells

catalog = load_spells()
fire_ball = catalog.get("fire_ball").mode("damage").effect
assert fire_ball.kind == "damage"
assert fire_ball.params == {"dice_per_level": "1d6", "element": "fire"}  # 1d6 per caster level

blind = catalog.get("light_mu").mode("blind").effect
assert (blind.kind, blind.condition) == ("condition", Condition.BLIND)

kind instance-attribute

kind: str

What casting does, one of EFFECT_KINDS.

condition class-attribute instance-attribute

condition: Condition | None = None

The Condition a condition effect puts on each target, like blind or charmed. None on every other kind.

cures_conditions class-attribute instance-attribute

cures_conditions: tuple[Condition, ...] = ()

The conditions a cure effect lifts. Cure light wounds' cure_paralysis mode lifts paralysed.

Casting releases each effect in the target's EffectsLedger that puts one of these conditions on it. Paralysis comes off however it was put on. Casting also removes a paralysed condition that has no ledger effect behind it, like one granted with grant_condition. The other conditions come off only with the ledger effect that granted them.

cures_effect_kinds class-attribute instance-attribute

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

The kinds of ledger effect a cure effect releases, by name.

This is for spells that cancel a named magic rather than a condition. Light's cancel mode releases "darkness".

modifiers class-attribute instance-attribute

modifiers: tuple[ModifierSpec, ...] = ()

The bonuses and penalties a modifiers effect gives, as ModifierSpec models.

A bonus to armour class or to saves, for example. They belong to the attached effect and end when it ends.

params class-attribute instance-attribute

params: Annotated[Mapping[str, int | str | bool | tuple[int | str, ...]], FrozenMap] = FrozenMap()

The numbers and options for this spell that casting reads for kind, keyed by name.

They include damage dice, per-level scaling, which creatures are eligible, how long after death a spell can revive, and area sizes. The keys differ by spell and by kind, so read them for the mode you have rather than expecting a fixed set.

SpellMode

Bases: BaseModel

One castable usage of a spell: what it targets, what it allows, and what it does.

Many SRD spell pages print more than one numbered usage. Cure light wounds heals or lifts paralysis, and light lights an area, blinds a creature, or cancels darkness. Each usage is a mode, and you choose one by its key, which is the mode argument of cast_spell. Get a spell's modes from SpellTemplate.modes, or one mode by key from SpellTemplate.mode.

A mode is either automated or manual, and the difference changes what casting does for you. An automated mode has both targeting and effect, and osrlib resolves it: it picks the targets, rolls the saves and the dice, applies the outcome, and attaches any lasting effect. A manual mode has manual=True, and in the built-in catalog it has no targeting and no effect, because the SRD page gives osrlib nothing to resolve. Casting a manual mode still spends the memorized copy and returns a CastResult with manual set and the mode's prose, and you decide what happens. Check manual before you promise a player an outcome.

Constructing one raises pydantic.ValidationError when manual is False and targeting or effect is None. It raises the same error for an automated up_to_n mode that can't size its group: its targeting has neither count nor count_dice, and its effect has no missiles_base param, which magic missile uses to count its missiles.

Examples:

from osrlib.data import load_spells

light = load_spells().get("light_mu")
assert [mode.key for mode in light.modes] == ["illuminate", "blind", "cancel"]
assert not any(mode.manual for mode in light.modes)

blind = light.mode("blind")
assert blind.save is not None  # the target may save against being blinded
assert blind.prose.startswith("Blinding a creature:")

key class-attribute instance-attribute

key: str = Field(min_length=1)

The mode's name, like "heal". No two modes of the same form have the same key.

Pass it as mode to cast_spell and validate_cast. A spell with a single usage still has a mode, like fire ball's "damage".

targeting class-attribute instance-attribute

targeting: TargetingSpec | None = None

Who the mode can affect and how many, as a TargetingSpec.

None only on a manual mode.

save class-attribute instance-attribute

save: SaveSpec | None = None

The saving throw the targets get, as a SaveSpec. None when the mode allows no save.

effect class-attribute instance-attribute

effect: SpellEffect | None = None

What the mode does, as a SpellEffect.

None only on a manual mode.

manual class-attribute instance-attribute

manual: bool = False

True when casting spends the copy and returns the event, and you decide the outcome.

prose class-attribute instance-attribute

prose: str = ''

The SRD text for this usage.

Show it to the player. For a manual mode, it's all the information osrlib has about the result.

SpellTemplate

Bases: BaseModel

One spell, compiled from its SRD page: the data that casting it uses.

Get one by id from SpellCatalog.get, or a class's whole list from SpellCatalog.by_list. The catalog comes from load_spells. Pass the template to validate_cast, cast_spell, or cast_from_scroll, and read its modes for the mode keys those calls accept.

A template is frozen and shared, and it doesn't change during play. What changes during play are the MemorizedSpell copies a caster has prepared and the effects a cast leaves on the ledger. Both refer to the template by id.

Constructing one raises pydantic.ValidationError when two modes of the same form have the same key.

Examples:

from osrlib.data import load_spells

fire_ball = load_spells().get("fire_ball")
assert (fire_ball.name, fire_ball.spell_list, fire_ball.level) == ("Fire Ball", "magic_user", 3)
assert [mode.key for mode in fire_ball.modes] == ["damage"]
assert fire_ball.range == "240’" and fire_ball.duration == "Instant"

id class-attribute instance-attribute

id: str = Field(min_length=1)

The id you look the spell up by, made from its name in lowercase with underscores, like "fire_ball".

A few spells appear in the SRD as a cleric page and a magic-user page with different rules. Each such pair is two entries: the cleric one has the suffix _c and the magic-user one _mu, like "light_c" and "light_mu". For the built-in ids, iterate load_spells().spells or see the spell id index.

name class-attribute instance-attribute

name: str = Field(min_length=1)

The spell's printed name, like "Cure Light Wounds". Show this, not the id.

spell_list class-attribute instance-attribute

spell_list: str = Field(pattern='^[a-z][a-z0-9_]*$')

Which class's spell list the spell belongs to, in lowercase letters, digits, and underscores.

The built-in catalog has "cleric" and "magic_user". A spell you write can use another list, for a class you write. It must match the CasterProfile.spell_list of any caster who memorizes or learns the spell.

level class-attribute instance-attribute

level: int = Field(ge=1, le=6)

The spell's level, 1 to 6.

A caster's slots are counted by spell level, not by the caster's level.

duration class-attribute instance-attribute

duration: str = Field(min_length=1)

The duration line as printed. Show this to a player.

duration_spec instance-attribute

duration_spec: DurationSpec

The structured form of duration, as a DurationSpec.

Casting reads it to set how long an attached effect lasts.

range class-attribute instance-attribute

range: str = Field(min_length=1)

The range line as printed. Show this to a player.

range_spec instance-attribute

range_spec: RangeSpec

The structured form of range, as a RangeSpec.

reversed_form class-attribute instance-attribute

reversed_form: ReversedForm | None = None

The spell's reverse, as a ReversedForm.

None when the spell doesn't reverse.

modes class-attribute instance-attribute

modes: tuple[SpellMode, ...] = Field(min_length=1)

One SpellMode per numbered usage on the page, in the page's order.

There's at least one. Their keys are the values casting accepts as its mode argument.

intro class-attribute instance-attribute

intro: str = ''

The page's opening text, above the numbered usages.

On a page with several usages, it's the lead-in, like "This spell has two usages:". On a page with one usage, it's the opening of the spell's description, and that mode's prose is the full text.

conjured_monsters class-attribute instance-attribute

conjured_monsters: tuple[MonsterTemplate, ...] = ()

Monster stat blocks printed on the spell's page rather than in the monster catalog.

The sticks to snakes page, for example, prints the snake's stat block. Spawn them with spawn_monster when you resolve the spell. Casting doesn't spawn them.

conjured_monster_ids class-attribute instance-attribute

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

Ids of monsters the spell summons that are in the monster catalog.

Look them up with load_monsters().get(monster_id). Conjure elemental lists its four elementals this way. Casting doesn't spawn them.

overrides_applied class-attribute instance-attribute

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

The field paths that a correction changed when this template was compiled from the SRD page.

Empty when the page compiled without corrections. It lists where the data departs from the SRD, for anyone checking it, and osrlib never reads it during play.

mode

mode(key: str, *, reversed: bool = False) -> SpellMode

Return one castable usage of the spell by its key.

Use this when you know which usage you want, to read its targeting, its save, or its prose before you cast it. To offer a player a choice instead, iterate modes and show each mode's prose. The key you pass here is the same string casting takes as its mode argument.

Parameters:

Name Type Description Default
key str

The mode's key, like "damage" or "blind". No two modes of one form share a key, but the normal and reversed forms are separate, so the reverse can reuse a key of the normal form or use different ones.

required
reversed bool

True to look in the spell's reversed form instead of its normal one.

False

Returns:

Type Description
SpellMode

The SpellMode.

Raises:

Type Description
ValueError

If reversed is True and the spell has no reversed form, or if the form has no mode with that key. The message includes the spell id, and the key when the key is missing. Read the form's modes for the keys it has.

Examples:

from osrlib.data import load_spells

cure = load_spells().get("cure_light_wounds")
assert cure.mode("heal").effect.params["dice"] == "1d6+1"
assert cure.mode("harm", reversed=True).effect.kind == "damage"
try:
    cure.mode("harm")  # "harm" is a mode of the reverse, not of the normal form
except ValueError as error:
    assert "no normal mode 'harm'" in str(error)

TargetingSpec

Bases: BaseModel

Who one castable usage of a spell can hit, and how many of them.

Read one from SpellMode.targeting to find out how many targets to collect before you call cast_spell. mode is the TargetingMode that select_targets also uses, and the other fields are the numbers that size and limit it for this spell.

The targets you pass to casting are candidates, not the final list. Casting drops the ones the mode can't affect and then applies mode to the rest, so an ineligible creature in the list uses up no Hit Dice and no place in a group. An ineligible target is therefore an outcome of the cast rather than a reason to refuse it. If no candidate is eligible, casting returns a CastResult with no_effect set, and the memorized copy is still spent.

Constructing one raises pydantic.ValidationError when count_dice or hd_budget_dice isn't a valid dice expression, and when the targeting could pick nobody:

  • count is below 1.
  • The mode is up_to_n, and count_dice can roll a total below 1.
  • The mode is hd_budget, and hd_budget_dice is None or can roll a total below 1.

up_to_n targeting with neither count nor count_dice builds, because magic missile's targeting has neither: the caster's level sets how many missiles it shoots. SpellMode refuses that targeting in an automated mode whose effect has no missiles_base param.

Examples:

from osrlib.core.combat import TargetingMode
from osrlib.data import load_spells

sleep = load_spells().get("sleep").mode("hd_budget").targeting
assert sleep.mode is TargetingMode.HD_BUDGET
assert (sleep.hd_budget_dice, sleep.hd_cap) == ("2d8", 4)

fire_ball = load_spells().get("fire_ball").mode("damage").targeting
assert fire_ball.mode is TargetingMode.AREA
assert (fire_ball.shape, fire_ball.dimensions) == ("sphere", {"radius_feet": 20})

mode instance-attribute

Which targeting mode the spell's mode uses, and so how many targets you pass.

  • self: no targets. The spell affects the caster.
  • single: exactly one target.
  • up_to_n: a group, sized by count or count_dice. Magic missile is the exception: it takes exactly one target per missile, and the same target can appear more than once.
  • hd_budget: as many creatures as a rolled pool of Hit Dice pays for.
  • area: every candidate you pass, which should be the creatures inside the area.
  • gaze: every candidate you pass, for a gaze that reaches everyone engaged with the gazer.

count class-attribute instance-attribute

count: int | None = Field(default=None, ge=1)

The fixed size of an up_to_n group, when the page prints a number rather than dice. At least 1.

count_dice class-attribute instance-attribute

count_dice: str | None = None

The dice rolled when the spell is cast to size an up_to_n group, on the magic stream.

Hold person's group mode is "1d4" and charm monster's is "3d6". In the up_to_n mode, the lowest total the dice can roll is at least 1.

hd_budget_dice class-attribute instance-attribute

hd_budget_dice: str | None = None

The dice rolled to size an hd_budget pool, like "2d8" for sleep. The hd_budget mode needs them, and the lowest total they can roll is at least 1.

The spell affects creatures in order of Hit Dice, fewest first, until the pool can't pay for the next one. The rest of the pool is lost rather than spent on anyone else.

hd_cap class-attribute instance-attribute

hd_cap: int | None = None

The most Hit Dice a creature may have and still be eligible.

Sleep's hd_budget mode sets 4, and charm monster's group mode sets 3.

hd_min class-attribute instance-attribute

hd_min: int | None = None

The fewest Hit Dice a creature must have to be eligible.

Charm monster's single-target mode sets 4, for the page's "more than 3 Hit Dice".

shape class-attribute instance-attribute

shape: str | None = None

The name of the area an area mode covers, like "sphere". None on every other mode.

dimensions class-attribute instance-attribute

The area's measurements in feet, keyed by name. Fire ball's sphere is {"radius_feet": 20}.

osrlib doesn't work out which creatures are inside the area. You decide who is caught and pass them as candidates.

TurnUndeadResult

Bases: BaseModel

What came of a turning attempt: the dice, the result for each kind of undead, and who fled.

turn_undead returns one. For an illegal attempt, it raises instead, so a result always describes an attempt that was made, and it has no accepted flag. Read outcomes to explain the result, and affected_ids to find the monsters to move.

roll instance-attribute

roll: int

The 2d6 total the cleric rolled to turn.

It's compared with the turning table's number for each kind of undead present, so one roll can turn some kinds and fail against others.

hd_pool class-attribute instance-attribute

hd_pool: int | None = None

The second 2d6 total: how many Hit Dice of undead the attempt can affect.

It's rolled when at least one kind came out turn or destroy. None when no kind did, and no second roll was made.

outcomes class-attribute instance-attribute

outcomes: tuple[TurningTypeOutcome, ...] = ()

One TurningTypeOutcome per kind of monster among the candidates.

They are in the order each kind first appears among the candidates. Each outcome is turn for a kind that flees, destroy for a kind destroyed outright, fail for a kind that held, and unaffected for a kind that isn't undead.

affected_ids class-attribute instance-attribute

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

The entity ids of the monsters the attempt reached, as many as hd_pool paid for.

A successful attempt reaches at least one living monster of a kind that came out turn or destroy, even when hd_pool is too small for it. Empty when no kind came out turn or destroy.

destroyed_ids class-attribute instance-attribute

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

The entity ids of the affected monsters that were destroyed rather than turned.

They are dead permanently, and raise dead can't bring them back.

events class-attribute instance-attribute

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

The UndeadTurnedEvent, then the events of what followed.

That's a death for each monster destroyed and an attached turned condition for each one that fled. Publish these.

add_spell_to_book

add_spell_to_book(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog, spell_id: str) -> SpellBookResult

Write a spell into an arcane caster's spell book.

An arcane caster prepares spells only from their spell book, so this is how they get more spells to choose from: when they gain a level, find a mentor, or copy a captured book. Call open_book_capacity first to show only the spell levels with room, and SpellCatalog.by_list to list what the class can learn. Once a spell is in the book, memorize_spells can prepare it.

At each spell level, the book has room for as many spells as the caster could memorize at that level, and it never has the same spell twice. A caster who loses levels keeps every spell in the book, and can add no more at a level until it has room again.

This function only writes the spell in. What learning costs and how long it takes are up to you, and this function doesn't charge money or spend game time. In a session, LearnSpell calls this function, and the command spends no game time either.

Parameters:

Name Type Description Default
caster Caster

The Caster learning the spell, a Character with an arcane class. The function adds one id to its spell_book. Nothing changes when the call is rejected.

required
definition ClassDefinition

The caster's class, as a ClassDefinition from load_classes.

required
catalog SpellCatalog

The spell catalog, from load_spells.

required
spell_id str

The spell to write in. For the ids the class may learn, call SpellCatalog.by_list, or see the spell id index for every built-in id.

required

Returns:

Type Description
SpellBookResult

A SpellBookResult. On success it has the book-updated event. Otherwise it has one rejection, and the book is unchanged. The rejection codes are magic.book.not_arcane for a class with no book, magic.book.unknown_spell, magic.book.wrong_list for a spell from another class's list, magic.book.duplicate for a spell already in the book, and magic.book.capacity_exceeded for a spell level with no room.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import add_spell_to_book
from osrlib.data import load_classes, load_spells

streams = RngStreams(master_seed=3)
catalog = load_spells()
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["sleep"],
).character
zelia.level = 3  # room for one more first-level spell

learned = add_spell_to_book(zelia, definition, catalog, "magic_missile")
assert learned.accepted
assert zelia.spell_book == ("sleep", "magic_missile")

refused = add_spell_to_book(zelia, definition, catalog, "cure_light_wounds")
assert [rejection.code for rejection in refused.rejections] == ["magic.book.wrong_list"]

cast_from_scroll

cast_from_scroll(
    reader: Caster,
    spell: SpellTemplate,
    mode: str,
    *,
    reversed: bool = False,
    targets: Sequence[Creature | str] = (),
    context: CastContext | None = None,
    ledger: EffectsLedger,
    clock: GameClock,
    allocator: Any,
    registry: dict[str, Any],
    ruleset: Ruleset,
    stream: RngStream,
    effects_stream: RngStream
) -> CastResult

Cast a spell off a scroll, with the scroll standing in for the memorized copy.

Use this rather than cast_spell when the spell is read off a scroll instead of cast from memory. The reader needs no memorized copy, no slot, and no ability to cast the spell. The legality checks, targeting, resolution, and CastResult are otherwise the same as for cast_spell.

You track the scroll. Reading a spell uses up that spell, because the words vanish from the page. osrlib has no model of the scroll, so mark the spell used yourself after this returns. Two other checks are yours too, or the UseItem command's in a session: whether this reader can read this scroll at all, which depends on a thief's scroll-reading ability and on whether the scroll is arcane or divine, and whether there is light to read by.

The whole read uses one caster level: the level minimum_caster_level returns for the spell, whatever the reader's level. The checks and the resolution both use it, so a fire ball off a scroll always does 5d6 damage, and a per-level duration uses the same level. The two checks that depend on caster level follow the scroll, not the reader:

  • How many targets a mode takes. Magic missile takes one target per missile, and the scroll's level gives one missile, so even a 6th-level reader passes one target, and three are refused.
  • How far a spell reaches when its printed range grows per level, when you give a distance_feet in the CastContext.

A condition, a modifier, or a wound the spell puts on its caster goes on the reader, as it would for a spell they had memorized.

Parameters:

Name Type Description Default
reader Caster

The Caster reading the scroll, which a Character satisfies. The function removes nothing from its memorized spells.

required
spell SpellTemplate

The SpellTemplate written on the scroll, from SpellCatalog.get.

required
mode str

Which usage of the spell, by its SpellMode.key.

required
reversed bool

True to cast the spell's reversed form.

False
targets Sequence[Creature | str]

The candidate targets, in your order: Creature values, which a Character and a MonsterInstance both satisfy, or location strings for spells you attach to a place.

()
context CastContext | None

The CastContext with the facts you state about the situation. None states nothing.

None
ledger EffectsLedger

The EffectsLedger that lasting effects attach to. Pass the same ledger every time.

required
clock GameClock

The GameClock, read to record when attached effects begin and end.

required
allocator Any

The IdAllocator that gives each attached effect its id. Pass the same allocator every time.

required
registry dict[str, Any]

Every live combatant by entity id, as Character and MonsterInstance objects.

required
ruleset Ruleset

The Ruleset in play.

required
stream RngStream

The RngStream the cast's draws come from, conventionally streams.get(MAGIC_STREAM).

required
effects_stream RngStream

The stream that attached effects draw from, conventionally streams.get(EFFECTS_STREAM).

required

Returns:

Type Description
CastResult

The CastResult: who was reached, and every event, in order.

Raises:

Type Description
ValueError

If validate_scroll_cast would return any rejection for the same arguments, or if no built-in class can cast spell. The message lists the rejection codes. The function draws and changes nothing before it raises. Call validate_scroll_cast first to get the reasons as rejections.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import GameClock
from osrlib.core.effects import EFFECTS_STREAM, 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.core.spells import MAGIC_STREAM, cast_from_scroll
from osrlib.data import load_monsters, load_spells

rules = Ruleset()
streams = RngStreams(master_seed=5)
catalog = load_spells()

# A 1st-level magic-user who could never memorize *fire ball* reads one off a scroll.
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["read_magic"],
).character
template = load_monsters().get("goblin")
goblin = spawn_monster(template, id="monster-0001", stream=streams.get(MONSTER_SPAWN_STREAM))

outcome = cast_from_scroll(
    zelia,
    catalog.get("fire_ball"),
    "damage",
    targets=[goblin],
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={"monster-0001": goblin},
    ruleset=rules,
    stream=streams.get(MAGIC_STREAM),
    effects_stream=streams.get(EFFECTS_STREAM),
)
assert outcome.affected_ids == ("monster-0001",)
assert goblin.current_hp == 0  # 5d6 at the scroll's caster level, and the goblin failed its save
assert zelia.memorized_spells == ()  # nothing was spent from memory

cast_spell

cast_spell(
    caster: Caster,
    spell: SpellTemplate,
    mode: str,
    *,
    profile: CasterProfile,
    reversed: bool = False,
    targets: Sequence[Creature | str] = (),
    context: CastContext | None = None,
    ledger: EffectsLedger,
    clock: GameClock,
    allocator: Any,
    registry: dict[str, Any],
    ruleset: Ruleset,
    stream: RngStream,
    effects_stream: RngStream
) -> CastResult

Cast a memorized spell: spend the copy, resolve the mode, and hand back what happened.

This is the module's entry point. Before you call it, the caster needs a memorized copy, from memorize_spells, and you need the profile caster_profile returns. Afterwards, publish the CastResult's events, and keep the ledger you passed. It now contains any effect the spell left running, and EffectsLedger.advance counts those effects down as game time passes. To cast a spell off a scroll, with no memorized copy, use cast_from_scroll instead.

The copy is spent whatever comes of the cast: when every target saves, when no target is eligible, and when a touch attack misses, because B/X has no rule for holding a spell back once it's cast. Call validate_cast first to find out whether the cast is legal without spending anything. For an illegal cast, this function raises instead of returning a refusal.

Which copy goes depends on the kind of caster. A divine caster spends any copy of the spell and chooses the form as they cast. An arcane caster chose the form when preparing, so the copy has to be in the form you ask for. Either way, the first matching copy in the caster's memorized_spells is spent.

Casting any spell ends the caster's invisibility before the new spell resolves, the same way attacking does.

The cast uses two RNG streams, kept separate so that each replays independently. Everything the cast rolls (targeting dice, damage dice, the touch attack, the targets' saving throws) comes from stream. Every roll for an attached effect, like a duration rolled as it attaches, comes from effects_stream.

Parameters:

Name Type Description Default
caster Caster

The Caster with a matching memorized copy, which a Character satisfies. That copy is removed from its memorized_spells.

required
spell SpellTemplate

The SpellTemplate to cast, from SpellCatalog.get.

required
mode str

Which usage of the spell, by its SpellMode.key.

required
profile CasterProfile

The caster's CasterProfile, from caster_profile.

required
reversed bool

True to cast the spell's reversed form.

False
targets Sequence[Creature | str]

The candidate targets, in your order: Creature values, which a Character and a MonsterInstance both satisfy, or location strings for spells you attach to a place. Casting drops the ineligible ones and then applies the mode's targeting to the rest, so for an area or group mode you can pass more candidates than the spell takes.

()
context CastContext | None

The CastContext with the facts you state about the situation. None states nothing.

None
ledger EffectsLedger

The EffectsLedger that lasting effects attach to. Pass the same ledger every time, not a new one, or the spell's effect is lost when you discard the new ledger.

required
clock GameClock

The GameClock, read to record when attached effects begin and end.

required
allocator Any

The IdAllocator that gives each attached effect its id. Pass the same allocator every time, so ids stay unique across the game.

required
registry dict[str, Any]

Every live combatant by entity id, as Character and MonsterInstance objects. Resolution uses it to change creatures other than the targets, like the creature an ending effect was on.

required
ruleset Ruleset

The Ruleset in play, read for the optional rules that change attack rolls and damage.

required
stream RngStream

The RngStream every draw the cast makes comes from, conventionally streams.get(MAGIC_STREAM).

required
effects_stream RngStream

The stream that attaching effects draw from, conventionally streams.get(EFFECTS_STREAM).

required

Returns:

Type Description
CastResult

The CastResult: who was reached, and every event, in order.

Raises:

Type Description
ValueError

If validate_cast would return any rejection for the same arguments. The message lists the rejection codes. The function spends, draws, and changes nothing before it raises. Retrying with the same arguments fails the same way, so call validate_cast first and offer only the casts it allows.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import GameClock
from osrlib.core.effects import EFFECTS_STREAM, 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.core.spells import MAGIC_STREAM, MemorizedSpell, cast_spell, caster_profile, memorize_spells
from osrlib.data import load_classes, load_monsters, load_spells

rules = Ruleset()
streams = RngStreams(master_seed=11)
catalog = load_spells()
definition = load_classes().get("magic_user")

# A 1st-level magic-user with *magic missile* in her book, memorized for the day.
created = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["magic_missile"],
)
zelia = created.character
prepared = memorize_spells(zelia, definition, catalog, [MemorizedSpell(spell_id="magic_missile")])
assert prepared.accepted

# One goblin target. The registry maps entity ids to the live objects.
template = load_monsters().get("goblin")
goblin = spawn_monster(template, id="monster-0001", stream=streams.get(MONSTER_SPAWN_STREAM))
outcome = cast_spell(
    zelia,
    catalog.get("magic_missile"),
    "missiles",
    profile=caster_profile(definition),
    targets=[goblin],
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={"monster-0001": goblin},
    ruleset=rules,
    stream=streams.get(MAGIC_STREAM),
    effects_stream=streams.get(EFFECTS_STREAM),
)
assert outcome.spell_id == "magic_missile" and not outcome.no_effect
assert outcome.affected_ids == ("monster-0001",)
assert zelia.memorized_spells == ()  # the cast spent the memorized copy
assert goblin.max_hp - goblin.current_hp == 3  # 1d6+1 missile damage, stable under this seed

caster_profile

caster_profile(definition: ClassDefinition) -> CasterProfile | None

Return how a class casts, or None if it casts nothing.

Call this first when you're about to do anything with a character's spells. The result shows whether the class casts at all, and it returns the profile argument that validate_cast and cast_spell take. Use a None answer to leave spells out of a fighter's interface. memorize_spells and add_spell_to_book return a rejection, not an error, for a class with no profile.

The answer comes from the class's ability tags, not from a list of built-in classes. A class you write casts when it has a divine_magic or arcane_magic ability. A ClassDefinition refuses such an ability without a spell_list in its params, and the profile's spell_list is that value.

Parameters:

Name Type Description Default
definition ClassDefinition

The class, as a ClassDefinition. For a character's class, pass Character.definition, which is the built-in class or the character's custom_class.

required

Returns:

Type Description
CasterProfile | None

The CasterProfile, or None when the class has neither casting tag.

Examples:

from osrlib.core.spells import caster_profile
from osrlib.data import load_classes

classes = load_classes()
magic_user = caster_profile(classes.get("magic_user"))
assert (magic_user.kind, magic_user.spell_list) == ("arcane", "magic_user")
assert caster_profile(classes.get("cleric")).kind == "divine"
assert caster_profile(classes.get("fighter")) is None

disrupt_casting

disrupt_casting(caster: Caster, spell_id: str, *, reversed: bool = False) -> list[Event]

Remove a spell a caster declared but was stopped from casting.

In the SRD, a caster who loses initiative and is then successfully attacked, or fails a saving throw, before their turn loses the spell they were casting, as though they had cast it. Call this when that happens. You decide that it happened. In a game session's battle, the osrlib.crawl package decides and calls this for you.

It resolves nothing and rolls nothing. It removes one memorized copy and returns one event. The copy it removes is the first one in the declared form, or, when there's none, the first copy of the spell in either form. That's how a divine caster's declared reverse costs them a normally prepared copy.

Parameters:

Name Type Description Default
caster Caster

The Caster who was interrupted, which a Character satisfies. The function removes one copy from its memorized_spells.

required
spell_id str

The id of the spell they declared, as it appears in a MemorizedSpell in the caster's memorized_spells. The spell id index lists the built-in ids.

required
reversed bool

True when the declared cast was of the reversed form.

False

Returns:

Type Description
list[Event]

A list with one SpellDisruptedEvent, to publish with whatever caused the disruption.

Raises:

Type Description
ValueError

If the caster has no memorized copy of that spell. Nothing changes. The caster can't have declared a spell they hadn't memorized, so check how you recorded the declaration.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import MemorizedSpell, disrupt_casting, memorize_spells
from osrlib.data import load_classes, load_spells

streams = RngStreams(master_seed=5)
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["magic_missile"],
).character
memorize_spells(zelia, definition, load_spells(), [MemorizedSpell(spell_id="magic_missile")])

events = disrupt_casting(zelia, "magic_missile")
assert [event.code for event in events] == ["magic.cast.disrupted"]
assert zelia.memorized_spells == ()  # gone, the same as if she had cast it

forget_excess_memorized

forget_excess_memorized(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> list[Event]

Remove the memorized copies a caster no longer has slots for.

Call this after anything that lowers a caster's level, which in B/X means energy drain. The caster's slots shrink with the level, and the spells they had prepared may no longer fit. This call removes the extra copies. drain_levels calls it for you. If you lower a caster's level some other way, call it yourself, or the caster keeps spells they no longer have slots for.

When everything still fits, nothing changes, so you can call this after any level change. Each spell level is counted separately: a caster who lost a second-level slot forgets a second-level spell and keeps their first-level ones.

The SRD doesn't say which copy goes, so osrlib removes the most recently prepared copies first, the ones at the end of the caster's memorized_spells. That choice depends only on the list, so it's the same on every replay.

Parameters:

Name Type Description Default
caster Caster

The Caster who lost levels, which a Character satisfies. The function removes copies from its memorized_spells.

required
definition ClassDefinition

The caster's class, as a ClassDefinition from load_classes. Its row for the caster's new level gives the slot counts.

required
catalog SpellCatalog

The spell catalog, from load_spells, used to look up the level of each memorized spell.

required

Returns:

Type Description
list[Event]

One SpellForgottenEvent per copy removed, the last-prepared copy first. Empty when everything still fits.

Raises:

Type Description
ValueError

If a memorized copy has a spell id that isn't in catalog. The message includes the id. Pass the catalog the copies came from.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import MemorizedSpell, forget_excess_memorized, memorize_spells
from osrlib.data import load_classes, load_spells

streams = RngStreams(master_seed=3)
catalog = load_spells()
definition = load_classes().get("cleric")
aldis = create_character(
    name="Aldis",
    class_id="cleric",
    alignment=Alignment.LAWFUL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character
aldis.level = 3  # two first-level slots
memorize_spells(
    aldis,
    definition,
    catalog,
    [MemorizedSpell(spell_id="cure_light_wounds"), MemorizedSpell(spell_id="light_c")],
)

aldis.level = 2  # drained back to one slot
forgotten = forget_excess_memorized(aldis, definition, catalog)
assert [event.spell_id for event in forgotten] == ["light_c"]  # the copy prepared last
assert aldis.memorized_spells == (MemorizedSpell(spell_id="cure_light_wounds"),)
assert forget_excess_memorized(aldis, definition, catalog) == []  # nothing left over

memorize_spells

memorize_spells(
    caster: Caster, definition: ClassDefinition, catalog: SpellCatalog, selections: Sequence[MemorizedSpell]
) -> MemorizationResult

Fill a caster's spell slots for the day, replacing whatever was memorized before.

Preparing comes before casting each day, and a caster with an empty memorized list can cast nothing. The list you pass replaces the old one entirely, because B/X has no way to refill one slot. A caster who casts one spell prepares the whole list again at the next opportunity. Then cast the copies with cast_spell.

What a caster may choose depends on the kind of caster, which caster_profile reports. A divine caster chooses from the whole class list and never marks a copy reversed, because they choose the form when casting. An arcane caster chooses only from their spell book, which add_spell_to_book adds to, and chooses each copy's form now. For both, the number of copies at each spell level must fit the slots for the caster's current level, and the same spell can be prepared more than once.

The rules about when a caster may prepare (once a day, after an uninterrupted night's sleep, over an hour) are part of exploration, so the PrepareSpells command in the crawl layer checks them. This function doesn't, so when you run the rules yourself, you decide when preparation is allowed.

Parameters:

Name Type Description Default
caster Caster

The Caster preparing spells, which a Character satisfies. This replaces its memorized_spells. Nothing changes when the call is rejected.

required
definition ClassDefinition

The caster's class, as a ClassDefinition from load_classes. Its progression row for the caster's level gives the slot counts.

required
catalog SpellCatalog

The spell catalog, from load_spells.

required
selections Sequence[MemorizedSpell]

The MemorizedSpell copies to prepare, in the order you want them stored. Casting spends the first matching copy, and forget_excess_memorized removes the last ones first.

required

Returns:

Type Description
MemorizationResult

A MemorizationResult. On success it has the memorized event. Otherwise it has every rejection found, and the caster is unchanged. The rejection codes are magic.memorize.not_a_caster, magic.memorize.unknown_spell, magic.memorize.wrong_list, magic.memorize.divine_reverses_at_cast, magic.memorize.not_in_book, magic.memorize.not_reversible, and magic.memorize.slots_exceeded.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import MemorizedSpell, memorize_spells
from osrlib.data import load_classes, load_spells

streams = RngStreams(master_seed=3)
catalog = load_spells()
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["sleep"],
).character

prepared = memorize_spells(zelia, definition, catalog, [MemorizedSpell(spell_id="sleep")])
assert prepared.accepted
assert zelia.memorized_spells == (MemorizedSpell(spell_id="sleep"),)

# A 1st-level magic-user has one first-level slot, so asking for two is refused whole.
refused = memorize_spells(
    zelia, definition, catalog, [MemorizedSpell(spell_id="sleep"), MemorizedSpell(spell_id="sleep")]
)
assert not refused.accepted
assert [rejection.code for rejection in refused.rejections] == ["magic.memorize.slots_exceeded"]
assert zelia.memorized_spells == (MemorizedSpell(spell_id="sleep"),)  # the old list stands

minimum_caster_level

minimum_caster_level(spell: SpellTemplate) -> int

Return the lowest class level that could cast a spell at all.

A spell read off a scroll resolves at this caster level, so validate_scroll_cast and cast_from_scroll call it for you. Call it yourself to show what a scroll will do before anyone reads it, because a spell's damage, duration, and number of targets depend on caster level.

The answer is the lowest level at which a class that uses the spell's list has a slot of the spell's level. It reads only the built-in classes from load_classes, so a class you write doesn't change it.

The SRD doesn't say at what level a scroll's spell was written. osrlib uses the lowest level that could cast it, so a scroll's spell is never stronger than the same spell cast by the lowest-level caster able to cast it. Neither validate_scroll_cast nor cast_from_scroll accepts a different level.

Parameters:

Name Type Description Default
spell SpellTemplate

The SpellTemplate to look up.

required

Returns:

Type Description
int

The caster level, 1 or higher.

Raises:

Type Description
ValueError

If no built-in class that uses the spell's list ever has a slot of the spell's level. That happens for a spell on a list you wrote, or for a spell level beyond every built-in class's slots.

Examples:

from osrlib.core.spells import minimum_caster_level
from osrlib.data import load_spells

catalog = load_spells()
assert minimum_caster_level(catalog.get("magic_missile")) == 1
assert minimum_caster_level(catalog.get("fire_ball")) == 5  # a fire ball scroll deals 5d6

open_book_capacity

open_book_capacity(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> tuple[int, ...]

Return how many more spells fit in an arcane caster's book, at each spell level.

Call this before you offer a player a spell to learn, so the menu shows only the spell levels with room. add_spell_to_book makes the same check and returns a rejection when there's no room. This function gives you the answer before that call.

At each spell level, a book has room for as many spells as the caster could memorize at that level. Entry i of the answer is the room left at spell level i + 1: the caster's current slot count there, minus the spells the book already has there, and never below zero.

A book loses no pages when its owner loses levels, so a drained caster can have more spells at a level than the level has room for. The count for that level is 0, and the caster can add nothing there until they regain levels.

Parameters:

Name Type Description Default
caster Caster

The Caster, which a Character satisfies. The function reads its spell_book and level and changes nothing.

required
definition ClassDefinition

The caster's class, as a ClassDefinition from load_classes.

required
catalog SpellCatalog

The spell catalog, from load_spells, used to look up the level of each spell in the book.

required

Returns:

Type Description
tuple[int, ...]

One count per spell level in the caster's spell_slots, lowest level first. An empty tuple for a class with no spell book, which is every divine caster and every class that casts nothing.

Raises:

Type Description
ValueError

If the book has a spell id that isn't in catalog. The message includes the id. Pass the catalog the book's spells came from.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import open_book_capacity
from osrlib.data import load_classes, load_spells

streams = RngStreams(master_seed=3)
catalog = load_spells()
classes = load_classes()
definition = classes.get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["sleep"],
).character

# One first-level slot, and the starting book already fills it.
assert open_book_capacity(zelia, definition, catalog) == (0, 0, 0, 0, 0, 0)
zelia.level = 3  # two first-level slots and one second-level
assert open_book_capacity(zelia, definition, catalog) == (1, 1, 0, 0, 0, 0)
assert open_book_capacity(zelia, classes.get("cleric"), catalog) == ()  # clerics keep no book

pop_mirror_image

pop_mirror_image(ledger: EffectsLedger, target_ref: str, *, registry: dict[str, Any], clock: GameClock) -> list[Event]

Destroy one of a caster's mirror images.

Mirror image surrounds its caster with illusory copies. In the SRD, each attack on the caster destroys one image, even if the attack misses. This module doesn't handle attacks, so call this once for each attack aimed at a caster who has images, in place of resolving that attack against the caster. In a game session's battle, the osrlib.crawl package calls this for you.

You can call it for anyone. For a target with no mirror images, it returns an empty list, so you don't need to check first. When the last image goes, the function releases the effect from the ledger, and the events from that release are in the returned list.

Parameters:

Name Type Description Default
ledger EffectsLedger

The EffectsLedger the cast attached the images' effect to.

required
target_ref str

The entity id of the caster being attacked.

required
registry dict[str, Any]

Every live combatant by entity id, as Character and MonsterInstance objects. Read when the last image goes and the effect is released.

required
clock GameClock

The GameClock, read for the current round, which the event records.

required

Returns:

Type Description
list[Event]

An EffectTickedEvent for the image destroyed, then the release events when it was the last one. Empty when the target has no images.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import GameClock
from osrlib.core.effects import EFFECTS_STREAM, EffectsLedger
from osrlib.core.monsters import IdAllocator
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import (
    MAGIC_STREAM,
    MemorizedSpell,
    cast_spell,
    caster_profile,
    memorize_spells,
    pop_mirror_image,
)
from osrlib.data import load_classes, load_spells

rules = Ruleset()
streams = RngStreams(master_seed=5)
catalog = load_spells()
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=rules,
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["magic_missile"],
).character
zelia.id = "pc-1"
zelia.level = 3
zelia.spell_book = ("magic_missile", "mirror_image")
memorize_spells(zelia, definition, catalog, [MemorizedSpell(spell_id="mirror_image")])

ledger = EffectsLedger()
clock = GameClock()
cast_spell(
    zelia,
    catalog.get("mirror_image"),
    "images",
    profile=caster_profile(definition),
    ledger=ledger,
    clock=clock,
    allocator=IdAllocator(),
    registry={"pc-1": zelia},
    ruleset=rules,
    stream=streams.get(MAGIC_STREAM),
    effects_stream=streams.get(EFFECTS_STREAM),
)
effect = ledger.active_on("pc-1", "mirror_image")[0]
assert effect.state["images"] == 2  # 1d4 images, stable under this seed

popped = pop_mirror_image(ledger, "pc-1", registry={"pc-1": zelia}, clock=clock)
assert [event.code for event in popped] == ["effects.effect.ticked"]
assert effect.state["images"] == 1
assert pop_mirror_image(ledger, "pc-2", registry={"pc-1": zelia}, clock=clock) == []

turn_undead

turn_undead(
    cleric: Caster,
    definition: ClassDefinition,
    candidates: Sequence[MonsterInstance],
    *,
    ledger: EffectsLedger,
    clock: GameClock,
    allocator: Any,
    registry: dict[str, Any],
    stream: RngStream
) -> TurnUndeadResult

Drive off or destroy undead with a cleric's holy symbol, the whole procedure in one call.

Turning isn't a spell and uses no slot, so the caster's memorized spells don't change. Call validate_turn_undead first, because an attempt the character can't make raises rather than returning a refusal. Afterwards, publish the result's events, and read affected_ids to move the undead that fled. How the monsters flee is up to you. This function only gives them the turned condition.

The attempt uses two rolls. First, one 2d6 roll is compared with the turning table once for each kind of monster among the candidates, not once per monster, because a whole kind either turns or doesn't. Some kinds turn automatically, some are destroyed outright, and some are beyond the cleric's power at their level.

If any kind came out turned or destroyed, a second 2d6 roll gives a pool of Hit Dice. The monsters of those kinds are affected in order of Hit Dice, fewest first, until the pool can't pay for the next one. Monsters with the same Hit Dice stay in the order you passed them in. The rest of the pool is lost rather than spent on anyone else, and a successful attempt always reaches at least one monster, even when the pool is too small for it.

Monsters of a kind that came out destroy die permanently, and raise dead can't bring them back. The others get the turned condition through an effect that doesn't end on its own and can't be dispelled. Release it from the ledger when the encounter ends. In a session, ending the encounter releases it.

Pass any monsters as candidates. A candidate that isn't undead comes out unaffected rather than causing a refusal, so an attempt can't be used to find out what is undead. A candidate that's already dead still counts toward its kind's result, but the Hit Dice pool skips it.

Parameters:

Name Type Description Default
cleric Caster

The Caster turning, which a Character satisfies. Its level picks the row of the turning table.

required
definition ClassDefinition

Their class, as a ClassDefinition from load_classes. It must have a turn_undead ability.

required
candidates Sequence[MonsterInstance]

The monsters present, as MonsterInstance objects. When the pool runs out, monsters with the same Hit Dice are taken in this order, so pass them in the same order every time to get the same result on a replay.

required
ledger EffectsLedger

The EffectsLedger the turned effects attach to. Pass the same ledger every time.

required
clock GameClock

The GameClock, read to record when the attached effects begin.

required
allocator Any

The IdAllocator that gives each attached effect its id.

required
registry dict[str, Any]

Every live combatant by entity id, as Character and MonsterInstance objects.

required
stream RngStream

The RngStream both 2d6 rolls come from, conventionally streams.get(MAGIC_STREAM). The player sees both rolls in the event, because in B/X the player rolls them.

required

Returns:

Type Description
TurnUndeadResult

The TurnUndeadResult: the rolls, the result for each kind, the monsters reached, and every event.

Raises:

Type Description
ValueError

If validate_turn_undead refuses the attempt, because the class can't turn undead, or the cleric is dead, petrified, paralysed, asleep, or weakened. The message lists the rejection code. The function rolls and changes nothing before it raises. Call validate_turn_undead first to get the reason as a rejection.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.clock import GameClock
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.core.ruleset import Ruleset
from osrlib.core.spells import MAGIC_STREAM, turn_undead
from osrlib.data import load_classes, load_monsters

streams = RngStreams(master_seed=12)
definition = load_classes().get("cleric")
aldis = create_character(
    name="Aldis",
    class_id="cleric",
    alignment=Alignment.LAWFUL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character

template = load_monsters().get("skeleton")
spawn = streams.get(MONSTER_SPAWN_STREAM)
skeletons = [spawn_monster(template, id=f"monster-000{n}", stream=spawn) for n in (1, 2, 3)]
result = turn_undead(
    aldis,
    definition,
    skeletons,
    ledger=EffectsLedger(),
    clock=GameClock(),
    allocator=IdAllocator(),
    registry={monster.id: monster for monster in skeletons},
    stream=streams.get(MAGIC_STREAM),
)
assert (result.roll, result.hd_pool) == (7, 4)  # met the threshold, then 4 Hit Dice of effect
assert [outcome.outcome for outcome in result.outcomes] == ["turn"]
assert result.affected_ids == ("monster-0001", "monster-0002", "monster-0003")
assert result.destroyed_ids == ()  # turned, not destroyed
assert all(has_condition(monster, Condition.TURNED) for monster in skeletons)

validate_cast

validate_cast(
    caster: Caster,
    spell: SpellTemplate,
    mode: str,
    *,
    profile: CasterProfile | None,
    reversed: bool = False,
    targets: Sequence[Creature | str] = (),
    context: CastContext | None = None,
    ledger: EffectsLedger | None = None
) -> list[Rejection]

Check whether a cast is legal, without casting it.

Call this to decide whether to offer a cast at all, to grey out a spell in a menu, or to explain to a player why they can't cast it. Then call cast_spell, which runs the same checks and raises if any fail, so a cast that passes here and is then made with the same arguments isn't refused.

This function draws nothing from an RNG stream and changes neither the caster nor the ledger, so you can call it as often as you like. It doesn't check whether a target is the kind of creature the spell affects. Casting settles that, because a check that rejected charm person aimed at a disguised doppelganger would tell the player what the doppelganger is. Such a cast is legal: it resolves, spends the copy, and affects nobody.

It checks these things:

  • The caster can cast. A dead, petrified, paralysed, asleep, silenced, feebleminded, weakened, bound, or gagged caster can't, and neither can a caster inside their anti-magic shell.
  • The caster has a memorized copy in the form asked for.
  • The spell has the form and the mode asked for.
  • The number of targets suits the mode. For magic missile, that's exactly one target per missile the caster's level gives.
  • Each target is a creature when the mode works only on creatures. A location string can't make a saving throw, take damage or healing, die, come back to life, or count against a pool of Hit Dice, and an effect on a location grants no condition or modifiers. Web, dispel magic, the modes that cure, and the modes that attach an effect with no condition or modifiers, like light's, still take a location.
  • The target is in range, but only when the context gives a distance.

It doesn't check for a cleric's holy symbol. In the SRD, a cleric carries one as part of their class, not as a condition of casting, so if you require one, check the inventory yourself.

Parameters:

Name Type Description Default
caster Caster

The Caster, which a Character satisfies. Read, never written.

required
spell SpellTemplate

The SpellTemplate to cast, from SpellCatalog.get.

required
mode str

Which usage of the spell, by its SpellMode.key. A key the chosen form doesn't have is a rejection, not an exception.

required
profile CasterProfile | None

The caster's CasterProfile, from caster_profile. Which memorized copies match depends on it: a divine caster's copy can be cast in either form, and an arcane caster's only in the form it was prepared in. None skips the memorized-copy check, which is how validate_scroll_cast calls this for a scroll.

required
reversed bool

True to cast the spell's reversed form.

False
targets Sequence[Creature | str]

The candidate targets: Creature values, which a Character and a MonsterInstance both satisfy, or location strings for spells you attach to a place rather than a creature. The checks count them and look for a location where the mode needs a creature. They don't check what kind of creature each one is.

()
context CastContext | None

The CastContext with the facts you state about the situation. None states nothing.

None
ledger EffectsLedger | None

The EffectsLedger, checked for an effect on the caster that prevents casting, like anti-magic shell. With None, the check finds no such effect, so pass the ledger that contains the caster's effects.

None

Returns:

Type Description
list[Rejection]

The reasons the cast is illegal, as Rejection models with a code and params. Empty when the cast may go ahead. A caster who can't cast, or a form or mode the spell doesn't have, returns that one rejection alone. The other checks each add a rejection, and each location where the mode needs a creature adds one. The codes are magic.cast.caster_incapacitated, magic.cast.caster_restrained, magic.cast.anti_magic_shell, magic.cast.not_reversible, magic.cast.unknown_mode, magic.cast.not_memorized, magic.cast.target_count, magic.cast.target_must_be_creature, and magic.cast.out_of_range. The params of magic.cast.target_must_be_creature are spell, mode, and the location in target.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.monsters import MONSTER_SPAWN_STREAM, spawn_monster
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import CastContext, MemorizedSpell, caster_profile, memorize_spells, validate_cast
from osrlib.data import load_classes, load_monsters, load_spells

streams = RngStreams(master_seed=5)
catalog = load_spells()
definition = load_classes().get("magic_user")
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["magic_missile"],
).character
memorize_spells(zelia, definition, catalog, [MemorizedSpell(spell_id="magic_missile")])
template = load_monsters().get("goblin")
goblin = spawn_monster(template, id="monster-0001", stream=streams.get(MONSTER_SPAWN_STREAM))

profile = caster_profile(definition)
missile = catalog.get("magic_missile")
assert validate_cast(zelia, missile, "missiles", profile=profile, targets=[goblin]) == []

# The same cast at a goblin 200 feet away, which is past the spell's 150 feet.
refused = validate_cast(
    zelia,
    missile,
    "missiles",
    profile=profile,
    targets=[goblin],
    context=CastContext(distance_feet=200),
)
assert [rejection.code for rejection in refused] == ["magic.cast.out_of_range"]
assert refused[0].params["range_feet"] == 150

validate_scroll_cast

validate_scroll_cast(
    reader: Caster,
    spell: SpellTemplate,
    mode: str,
    *,
    reversed: bool = False,
    targets: Sequence[Creature | str] = (),
    context: CastContext | None = None,
    ledger: EffectsLedger | None = None
) -> list[Rejection]

Check whether reading a scroll is legal, without reading it.

This is validate_cast for a spell read off a scroll, and cast_from_scroll makes the same check before it resolves anything. Call it to decide whether to offer a read, and before every read. osrlib has no model of the scroll, so call this before you mark the scroll used: cast_from_scroll raises on an illegal read.

It differs from validate_cast in the caster level it checks at. A scroll's spell resolves at the level minimum_caster_level returns, whatever the reader's level, so this runs validate_cast for a caster of that level. The two checks that depend on caster level follow the scroll's level. One is how many targets a mode takes, so a 6th-level reader of a magic missile scroll passes one target, and three are refused. The other is how far a per-level range reaches. The memorized-copy check is skipped, because the scroll takes the place of the copy.

It doesn't check two things that depend on the game rather than on the spell: whether this reader can read this scroll at all, which depends on a thief's scroll-reading ability and on whether the scroll is arcane or divine, and whether there's light to read by. In a session, the UseItem command checks both.

Parameters:

Name Type Description Default
reader Caster

The Caster reading the scroll, which a Character satisfies. Read, never changed.

required
spell SpellTemplate

The SpellTemplate written on the scroll, from SpellCatalog.get.

required
mode str

Which usage of the spell, by its SpellMode.key. A key the chosen form doesn't have is a rejection, not an exception.

required
reversed bool

True to ask about the spell's reversed form.

False
targets Sequence[Creature | str]

The candidate targets, Creature values or location strings, as cast_from_scroll takes them. The checks count them and look for a location where the mode needs a creature, as validate_cast does. Leave it out for a spell with no targets.

()
context CastContext | None

The CastContext with the facts you state about the situation. None states nothing.

None
ledger EffectsLedger | None

The EffectsLedger, checked for an effect on the reader that prevents casting. With None, the check finds no such effect, so pass the ledger that contains the reader's effects.

None

Returns:

Type Description
list[Rejection]

The reasons the read is illegal, as Rejection models with a code and params, the same codes validate_cast returns. Empty when the read may go ahead, which means cast_from_scroll with the same arguments won't raise.

Raises:

Type Description
ValueError

If minimum_caster_level raises for spell, because no built-in class can cast it.

Examples:

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

streams = RngStreams(master_seed=5)
zelia = create_character(
    name="Zelia",
    class_id="magic_user",
    alignment=Alignment.NEUTRAL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
    starting_spell_ids=["read_magic"],
).character
zelia.level = 6  # three missiles from memory, one off a 1st-level scroll
template = load_monsters().get("goblin")
spawns = streams.get(MONSTER_SPAWN_STREAM)
goblins = [spawn_monster(template, id=f"monster-000{number}", stream=spawns) for number in (1, 2, 3)]
missile = load_spells().get("magic_missile")

refused = validate_scroll_cast(zelia, missile, "missiles", targets=goblins)
assert [rejection.code for rejection in refused] == ["magic.cast.target_count"]
assert refused[0].params["expected"] == 1  # the scroll's level, not the reader's
assert validate_scroll_cast(zelia, missile, "missiles", targets=goblins[:1]) == []

validate_turn_undead

validate_turn_undead(cleric: Caster, definition: ClassDefinition) -> list[Rejection]

Check whether a character may attempt to turn undead, without rolling.

Call this to decide whether to offer turning as an action at all. Then call turn_undead, which runs the same checks and raises if any fail. This function rolls no dice and changes nothing.

Two things can stop an attempt. The character's class may not turn undead: a class can only if it has a turn_undead ability, so a class you write gets the power when you add that ability. Or the character may be unable to present a holy symbol, because they are dead, petrified, paralysed, asleep, or weakened. Weakened is the state raise dead leaves a character in, and it prevents class abilities.

It doesn't check whether the character has a holy symbol. In the SRD, a cleric carries one as part of their class, not as a condition of turning, so if you require one, check the inventory yourself.

Parameters:

Name Type Description Default
cleric Caster

The Caster attempting the turning, a Character whose class can turn undead. Read, never changed.

required
definition ClassDefinition

Their class, as a ClassDefinition from load_classes.

required

Returns:

Type Description
list[Rejection]

Why the attempt can't be made, as Rejection models with a code and params. Empty when the attempt may go ahead. There's at most one, because the call stops at the first problem: magic.turning.not_a_turner for a class that can't turn undead, or magic.turning.caster_incapacitated, whose condition param gives the condition.

Examples:

from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.core.spells import validate_turn_undead
from osrlib.data import load_classes

streams = RngStreams(master_seed=5)
classes = load_classes()
aldis = create_character(
    name="Aldis",
    class_id="cleric",
    alignment=Alignment.LAWFUL,
    ruleset=Ruleset(),
    stream=streams.get(CHARACTER_CREATION_STREAM),
).character

assert validate_turn_undead(aldis, classes.get("cleric")) == []
refused = validate_turn_undead(aldis, classes.get("fighter"))
assert [rejection.code for rejection in refused] == ["magic.turning.not_a_turner"]