osrlib.core.items
Equipment, inventories, magic items, identification, and curses.
The models and functions in this module turn the two item catalogs that
load_equipment and
load_magic_items return into what a
character carries. Start at Inventory, which contains one
character's items, coins, and equipped slots. Every character built by
create_character has one inventory, and
combat resolution in osrlib.core.combat reads the templates
here to score an attack.
The functions, in the order you use them:
EquipmentCatalog.gettakes an equipment id and returns its template.purchasetakes an inventory and a template, charges the purse, and returns the newItemInstance.validate_purchasereturns the reasons a purchase would fail instead of raising, as a list that's empty when it would succeed.equipandunequipmove an instance into use and back.validate_equipandvalidate_unequipreturn the reasons a move would fail instead of raising, as a list that's empty when it would succeed.magic_item_templatetakes a magic item instance and returns its template.equipped_item_modifierstakes an inventory and returns the stat modifiers its worn magic items grant.movement_rate_feettakes an inventory and aRulesetand returns the exploration movement rate.encounter_movement_rateturns that into the rate for one combat round, andtracked_weight_coinsreturns the weight behind it.
In a running game you drive all of this through commands
(PurchaseEquipment,
EquipItem,
UnequipItem), which validate, emit events, and
record the change in the save. Call the functions here directly when you're using the
rules without a session.
The catalogs and their templates are frozen and shared, so a template never changes during play. Each item in play is an
instance made from one: ItemInstance for mundane
equipment, MagicItemInstance for magic items.
A magic item instance starts unidentified. In a session, the engine reveals a cursed item's curse
the first time a character uses the item. From then on the bearer can't take the item off until the
remove curse spell lifts the curse.
validate_equip enforces what a class may wear or
wield: armour and weapon policies, the two-ring cap, and the rule that a two-handed weapon
and a shield can't be used together.
Torch, holy water, and burning oil appear on both the OSE SRD's weapon table and its gear
list. In osrlib, each is one gear item with one id. Its combat field contains its combat
stats, as a CombatFacet. The weapon catalog
lists only the other weapons. Class weapon policies apply only to that catalog, so a cleric
may use holy water and a magic-user may throw oil or swing a torch. This is an adaptation, a
reading osrlib chooses where the rules are unclear (see the
adaptations register).
All weights are in coins, the OSE SRD's unit of encumbrance at ten coins to the pound.
Coins themselves weigh 1 each. The encumbrance setting of
Ruleset picks what is weighed: nothing, treasure alone
(basic), or treasure and equipment (detailed). Under basic and detailed encumbrance, a
character whose tracked weight is above the maximum load can't move. The maximum load is
MAX_LOAD_COINS. Under detailed encumbrance, worn
gauntlets of ogre power raise it. osrlib doesn't cap how much an inventory contains.
Typical usage:
from osrlib.core.items import Inventory, equip, movement_rate_feet, purchase
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes, load_equipment
catalog = load_equipment()
fighter = load_classes().get("fighter")
inventory = Inventory()
inventory.purse.gp = 100
plate = purchase(inventory, catalog.get("plate_mail"))
sword = purchase(inventory, catalog.get("sword"))
torches = purchase(inventory, catalog.get("torch"))
equip(inventory, fighter, plate)
equip(inventory, fighter, sword)
print(torches.quantity, inventory.purse.gp, movement_rate_feet(inventory, Ruleset()))
# 6 29 60
AnyInstance
module-attribute
AnyInstance = Annotated[ItemInstance | MagicItemInstance, Field(discriminator='instance_type')]
Any owned item, mundane or magic, told apart by its instance_type field.
This is what an Inventory contains: its item list, its
armour and shield slots, and its wielded list take either kind, because a character
wields a sword and a sword +1 the same way. Its ring slots take magic items only. Because
the union is discriminated, pydantic reads a saved inventory back as the right classes,
and a match on instance_type covers both cases.
The members are ItemInstance and
MagicItemInstance. Only a magic instance has an
instance id. A mundane one is identified by its template.
BASE_MOVEMENT_FEET
module-attribute
The unencumbered exploration movement rate in feet per turn, printed as 120' (40').
movement_rate_feet returns this under basic
encumbrance for an unarmoured character who isn't hauling treasure, and under detailed
encumbrance for a load of 400 coins or less. It always returns this when the ruleset's
encumbrance setting is none. The 40' in parentheses is the encounter rate, a third of the base, which
encounter_movement_rate computes.
COIN_VALUES_CP
module-attribute
What one coin of each denomination is worth in copper pieces.
The keys are the denomination names the purse and the treasure tables use (pp, gp,
ep, sp, cp). CoinPurse and
Coins convert with it, and
CoinPurse.spend pays and makes change in these
values. osrlib does all coin arithmetic in copper, so mixed purses convert without rounding.
The experience award for treasure is 1 XP per gold piece of value.
ItemTemplate
module-attribute
ItemTemplate = Annotated[
WeaponTemplate | ArmourTemplate | GearTemplate | AmmunitionTemplate, Field(discriminator="item_type")
]
Any one of the four mundane equipment templates, told apart by its item_type field.
Annotate a parameter or a field with this when it takes equipment of any kind:
purchase and
validate_purchase do, and so does the items
field of Adventure. Because the union is
discriminated, pydantic reads a serialized item back as the right class without
guessing, and a match on item_type covers every case.
The members are WeaponTemplate,
ArmourTemplate,
GearTemplate, and
AmmunitionTemplate. Only weapons, armour, and
ammunition have a weight. Only gear and ammunition have a lot size.
MAX_LOAD_COINS
module-attribute
The most a character can carry in coins of weight before movement drops to 0.
Ten coins weigh a pound, so this is 160 pounds. Every weight the functions in this module
return is in coins. Under basic and detailed encumbrance,
movement_rate_feet returns 0 above this figure,
and the slowest band of detailed encumbrance ends here. osrlib doesn't stop you from
putting more in an Inventory, but the movement rate is
then 0. Under detailed encumbrance, worn gauntlets of ogre power raise this limit, and every
band below it, by 1,000 coins.
MAX_RINGS_WORN
module-attribute
How many magic rings a character can wear at once: one on each hand.
In the tabletop rules, none of a character's rings work while they wear more than two. So
instead of letting a third ring on, validate_equip
rejects it with items.ring.hands_full when you pass it the inventory.
equip always passes the inventory, so it raises on a third
ring.
MISC_GEAR_WEIGHT_COINS
module-attribute
The flat weight in coins that any amount of miscellaneous gear adds under detailed encumbrance.
The SRD lists a weight for each weapon and suit of armour but none for adventuring gear.
So equipment_weight_coins adds this figure
once when a character carries any gear at all, however much gear that is.
AmmunitionTemplate
Bases: BaseModel
Ammunition for a missile weapon: arrows, quarrels, sling stones.
Bought like gear, in lots: one purchase at the listed price delivers lot_size
units. Compiled ammunition weighs nothing, because the SRD counts the weight of the
ammunition and its container in the missile weapon's listed weight and gives the
ammunition table no weight column. Ammunition can't be equipped: wield the bow, and
the arrows stay in the item list. Sling stones are free, so their compiled cost is 0.
item_type
class-attribute
instance-attribute
item_type: Literal['ammunition'] = 'ammunition'
Always "ammunition".
id
instance-attribute
id: str
The catalog id, for example "arrows". Get every id from load_equipment, or see
the equipment id index.
name
instance-attribute
name: str
The display name as the price list prints it, which includes the lot: "Arrows (quiver of 20)".
cost_gp
class-attribute
instance-attribute
The listed price in gold pieces, for one lot. 0 for sling stones.
lot_size
class-attribute
instance-attribute
How many units one purchase delivers, for example 20 arrows.
weight_coins
class-attribute
instance-attribute
The weight in coins for one unit. 0 on every compiled template. Ammunition you bundle with an adventure can set a
weight, and equipment_weight_coins counts it per unit.
material
class-attribute
instance-attribute
What the ammunition is made of, for monsters that only silver or magic can hurt. See
Material.
ArmourCategory
Bases: StrEnum
How bulky a suit of body armour is, for the basic encumbrance rates.
Under basic encumbrance, a character's movement rate depends on the armour they wear
rather than on the weight they carry.
movement_rate_feet reads the category of the
armour in the worn slot to pick the rate. No member stands for wearing nothing: an empty
worn slot means the unarmoured rate. The shield has no category. A character in
enchanted armour moves at the rate of the mundane armour it's made from, because
enchantment halves a suit's weight without making it less bulky.
The values "light" and "heavy" appear in the compiled equipment data.
ArmourTemplate
Bases: BaseModel
A suit of body armour or the shield, from the SRD's armour table.
Body armour sets a wearer's armour class outright and a shield adds a bonus to it, so
one of the two field groups is filled and the other is empty: body armour has ac,
ac_ascending, and category, while the shield has ac_bonus alone. Use
is_shield to tell which kind you have
instead of testing the fields. Get one from
EquipmentCatalog.get, buy it with
purchase, and put it on with
equip, which routes body armour to the worn slot and the
shield to the shield slot.
Both armour class formats are here because the tabletop rules print both: the descending scale, where lower is better and unarmoured is 9, and the ascending scale in brackets, where higher is better and unarmoured is 10. You choose which one to show players. The rules give the same result either way.
item_type
class-attribute
instance-attribute
item_type: Literal['armour'] = 'armour'
Always "armour".
id
instance-attribute
id: str
The catalog id, for example "plate_mail". Get every id from
load_equipment, or see the equipment id
index.
cost_gp
class-attribute
instance-attribute
The listed price in gold pieces.
weight_coins
class-attribute
instance-attribute
The weight in coins. Enchanted armour weighs half this.
ac
class-attribute
instance-attribute
ac: int | None = None
Body armour's armour class on the descending scale. None on the shield.
ac_ascending
class-attribute
instance-attribute
ac_ascending: int | None = None
The same protection on the ascending scale. None on the shield.
ac_bonus
class-attribute
instance-attribute
ac_bonus: int | None = None
The shield's bonus to armour class, 1 on the compiled shield. It lowers descending AC and raises ascending AC
by that much. None on body armour.
category
class-attribute
instance-attribute
category: ArmourCategory | None = None
How bulky the suit is, for the basic encumbrance movement rates. See
ArmourCategory. None on the shield.
overrides_applied
class-attribute
instance-attribute
Which fields were corrected when this row was compiled from the SRD text, as dotted paths. Empty when none were. osrlib doesn't read it during play.
is_shield
property
is_shield: bool
Whether this row is the shield rather than a suit of body armour.
Read it instead of testing the armour class fields yourself: the shield has an
armour class bonus and body armour has base values, and
equip sends the two to different slots.
Returns:
| Type | Description |
|---|---|
bool
|
True for the shield, False for body armour. |
ArmourTypeRow
Bases: BaseModel
One band of the Magic Armour Type table, which gives the mundane armour a generated suit is made of.
The bands are in MagicArmourTypeTable.rows.
MagicArmourTypeTable.base_for_roll
reads them for a d8 roll, so read a band directly only to show the table.
roll_min
class-attribute
instance-attribute
The lowest d8 result in this band.
roll_max
class-attribute
instance-attribute
The highest d8 result in this band.
base_item_id
instance-attribute
base_item_id: str
The mundane armour the band yields, for example "chainmail". Look it up with
load_equipment, or see the equipment id
index.
CoinPurse
Bases: BaseModel
The coins a character is carrying, by denomination.
Every Inventory has one. Unlike
Coins, it's mutable, because this is the money that gets
spent. Call can_afford before
you charge, and spend to charge. Both work in
whole gold pieces, the unit the equipment lists price in.
Paying takes the smallest coins first, and change comes back as the fewest coins that make it up. Each coin weighs 1 whatever its metal, so spending small coins first lightens the purse. A purse full of copper slows a character down.
pp
class-attribute
instance-attribute
Platinum pieces, worth 5 gp each.
ep
class-attribute
instance-attribute
Electrum pieces, worth half a gold piece each.
sp
class-attribute
instance-attribute
Silver pieces, ten to the gold piece.
cp
class-attribute
instance-attribute
Copper pieces, a hundred to the gold piece.
value_cp
property
value_cp: int
What the purse is worth in copper pieces.
osrlib does coin arithmetic in copper, because totalling a mixed purse in gold would lose the odd silver and copper to rounding.
Returns:
| Type | Description |
|---|---|
int
|
The value in copper pieces. |
total_coins
property
total_coins: int
How many coins are in the purse, which is also its weight in coins.
Every coin weighs 1 whatever its metal, so this figure goes straight into
treasure_weight_coins.
Returns:
| Type | Description |
|---|---|
int
|
The number of coins. |
can_afford
Return whether the purse can cover a price in gold pieces.
Call this before you charge: spend raises rather than
going into debt. Coins of every denomination count, so a purse with no gold at all can
still afford a gold-priced item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_gp
|
int
|
The price in whole gold pieces. Not negative. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when the purse is worth at least that much. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
spend
spend(cost_gp: int) -> None
Pay a price in gold pieces out of the purse, making change.
Mutates the purse. Coins go out smallest denomination first. Any overpayment comes back as the fewest coins that make up the difference, largest denomination first. For example, paying 1 gp from a purse of two gold and five silver spends the five silver, then a gold piece to cover the rest, and returns the change as one electrum piece. The result is deterministic and preserves value exactly, so a purse can be spent from and saved without drifting.
purchase calls this for you when a character buys
equipment. Call it directly for anything else you charge for, like lodging or
travel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_gp
|
int
|
The price in whole gold pieces. Not negative. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Coins
Bases: BaseModel
A fixed pile of coins, like generated treasure, the contents of a chest, or a pile dropped on the floor.
Frozen, unlike the CoinPurse a character carries.
generate_treasure returns its coins in this
form, and a dungeon feature contains its coins this way until someone picks them up. To
give the coins to a character, add each denomination to their purse.
pp
class-attribute
instance-attribute
Platinum pieces, worth 5 gp each.
ep
class-attribute
instance-attribute
Electrum pieces, worth half a gold piece each.
sp
class-attribute
instance-attribute
Silver pieces, ten to the gold piece.
cp
class-attribute
instance-attribute
Copper pieces, a hundred to the gold piece.
total_coins
property
total_coins: int
How many coins are in the pile, whatever they are worth.
This is also its weight in coins, since every coin weighs 1 whatever its metal.
Returns:
| Type | Description |
|---|---|
int
|
The number of coins. |
CombatFacet
Bases: BaseModel
The combat statistics of a piece of gear that can also be used as a weapon.
Torch, holy water, and burning oil are printed on both the SRD's weapon table and its
gear list. osrlib compiles each as one gear item whose combat field contains this facet,
so the item has a single id and a single weight. Attack resolution reads the facet's
damage, qualities, and ranges as it reads those of a
WeaponTemplate. Class weapon policies don't apply
to it, so a cleric may throw holy water and a magic-user may swing a torch. That
exemption is an adaptation, a reading osrlib chooses where the rules are unclear (see
the adaptations register).
qualities
instance-attribute
qualities: tuple[WeaponQuality, ...]
What the item can do when used as a weapon. See WeaponQuality. Holy water
and burning oil have the splash quality, which makes them damage the target again the following round.
missile_ranges
class-attribute
instance-attribute
missile_ranges: MissileRanges | None = None
The three range bands, present exactly when qualities includes the missile quality.
EquipmentCatalog
Bases: BaseModel
The whole mundane equipment list, which is what a shop sells and what a character can buy.
Call load_equipment to get the compiled catalog. It's
frozen, and every call returns the same cached object. Look up an item by id with
get, or iterate a list when you are
building a shop screen. A GameSession that plays an
Adventure with bundled item templates looks items up
in a catalog with those templates added.
Ids are unique across the four equipment lists, and building a catalog with a repeated
id raises a pydantic ValidationError. No compiled equipment id is also a magic item
id, so an id refers to exactly one thing anywhere in the library.
armour
instance-attribute
armour: tuple[ArmourTemplate, ...]
Every suit of body armour, plus the shield.
treasure_weights
instance-attribute
treasure_weights: tuple[TreasureWeight, ...]
What each kind of treasure weighs. See TreasureWeight.
get
get(item_id: str) -> WeaponTemplate | ArmourTemplate | GearTemplate | AmmunitionTemplate
Return the template with item_id, whichever of the four lists contains it.
Use this whenever you have an id and need the item: before
purchase, when rendering what a character carries, or
when resolving an id an adventure supplied. Lookup is a scan, so hoist it out of a hot
loop if you're resolving many ids at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_id
|
str
|
Any equipment id this catalog contains. For the compiled catalog
( |
required |
Returns:
| Type | Description |
|---|---|
WeaponTemplate | ArmourTemplate | GearTemplate | AmmunitionTemplate
|
The template. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no item has that id. The message includes the id. |
Examples:
GearTemplate
Bases: BaseModel
A piece of adventuring gear: a torch, a rope, a backpack, a flask of oil.
Every item on the equipment list that isn't a weapon, armour, or ammunition is gear. Get
one from EquipmentCatalog.get and buy it
with purchase. Gear sells in lots: one purchase at the
listed price delivers lot_size units, so buying torches once costs 1 gp and yields
six torches in one ItemInstance.
equip accepts only gear with a combat facet: the torch,
holy water, and burning oil. Gear has no per-item weight in the SRD, so detailed
encumbrance adds a flat
MISC_GEAR_WEIGHT_COINS once for carrying
any of it.
id
instance-attribute
id: str
The catalog id, for example "torch". Get every id from load_equipment, or see
the equipment id index.
name
instance-attribute
name: str
The display name as the price list prints it, which includes the lot size for gear sold in lots:
"Torches (6)", "Iron spikes (12)".
cost_gp
class-attribute
instance-attribute
The listed price in gold pieces, for one lot.
lot_size
class-attribute
instance-attribute
How many units one purchase at cost_gp delivers. 1 for gear sold singly.
capacity_coins
class-attribute
instance-attribute
capacity_coins: int | None = None
How much fits in the container, in coins of weight, where the SRD gives a figure (backpack, small sack, large
sack). None for gear that contains nothing. osrlib doesn't enforce the figure, so if you want container
limits, enforce them yourself.
combat
class-attribute
instance-attribute
combat: CombatFacet | None = None
The combat statistics for the three items that are also weapons. See
CombatFacet. None for everything else.
params
class-attribute
instance-attribute
The exploration mechanics the SRD's gear table prints, keyed by name: a torch's burn_turns and
light_radius_feet, the tinder box's light_chance_in_six, and so on. The dungeon-crawl procedures in
osrlib.crawl.exploration read these.
GeneratedTreasure
Bases: BaseModel
Everything one roll of a treasure table produced.
generate_treasure,
generate_unguarded_treasure, and
generate_treasure_entries return
one. These functions don't place the treasure or give it to anyone. Put the coins in a purse, the valuables and
magic items in an
Inventory, or keep the whole thing in a dungeon feature
until the party opens it. Any of the three fields can be empty, and an unlucky roll
leaves all three empty.
coins
class-attribute
instance-attribute
The coins, by denomination. See Coins.
valuables
class-attribute
instance-attribute
valuables: tuple[ValuableInstance, ...] = ()
The gems and jewellery. See ValuableInstance.
magic_items
class-attribute
instance-attribute
magic_items: tuple[MagicItemInstance, ...] = ()
The magic items, already rolled up as instances. See MagicItemInstance.
Inventory
Bases: BaseModel
Everything one character carries, including items, coins, valuables, and what is in hand or worn.
Every Character has one. Build it up with
purchase and equip, search
it with carried_item and
magic_item, and weigh it with
tracked_weight_coins or
movement_rate_feet. In a running game the
commands do all of this and record it in the save.
To give a character treasure you generated outside a session, append each magic item to
items and each valuable to valuables, and add each denomination of the coins to the
matching field of purse.
An instance is in exactly one place: equipping moves it out of the item list and into
its slot, and unequipping moves it back. So iterate
all_instances rather than items when
you want everything a character has. The item list is in the order items were added,
and an unequipped item goes back on the end.
osrlib doesn't cap what a character can carry. Weight affects the movement rate instead.
Past the maximum load, the character can't move. The maximum load is
MAX_LOAD_COINS. Under detailed encumbrance, worn
gauntlets of ogre power raise it.
items
class-attribute
instance-attribute
items: list[AnyInstance] = []
What is carried but not in use, in the order it was acquired. See AnyInstance.
valuables
class-attribute
instance-attribute
valuables: list[ValuableInstance] = []
Carried gems and jewellery. See ValuableInstance.
worn_armour
class-attribute
instance-attribute
worn_armour: AnyInstance | None = None
The suit of body armour being worn, or None.
shield
class-attribute
instance-attribute
shield: AnyInstance | None = None
The shield being carried, or None.
wielded
class-attribute
instance-attribute
wielded: list[AnyInstance] = []
Everything equipped that isn't armour, a shield, or a ring: weapons, a torch, a wand, and worn miscellaneous magic items like gauntlets. A two-handed weapon here rules out a shield.
rings
class-attribute
instance-attribute
rings: list[MagicItemInstance] = []
The worn rings, at most MAX_RINGS_WORN.
all_instances
all_instances() -> list[ItemInstance | MagicItemInstance]
Return every instance the character has, carried or equipped.
Use it whenever "what does this character have" is the question: weighing a load,
looking for an item, rendering a character sheet. Equipped items aren't in items, so
reading that field alone misses the sword in hand.
Returns:
| Type | Description |
|---|---|
list[ItemInstance | MagicItemInstance]
|
A new list: the item list first, then worn armour, the shield, what is wielded, and the rings. The order is stable, so anything that iterates it behaves the same on replay. |
Examples:
from osrlib.core.items import CoinPurse, Inventory, equip, purchase
from osrlib.data import load_classes, load_equipment
catalog = load_equipment()
inventory = Inventory(purse=CoinPurse(gp=50))
sword = purchase(inventory, catalog.get("sword"))
purchase(inventory, catalog.get("rope"))
equip(inventory, load_classes().get("fighter"), sword)
print([instance.template.id for instance in inventory.items])
# ['rope']
print([instance.template.id for instance in inventory.all_instances()])
# ['rope', 'sword']
equipped_instances
equipped_instances() -> list[ItemInstance | MagicItemInstance]
Return only what the character has in use.
This is the set that grants bonuses:
equipped_item_modifiers scans exactly
this. For everything a character has, carried items included, call
all_instances.
Returns:
| Type | Description |
|---|---|
list[ItemInstance | MagicItemInstance]
|
A new list: worn armour, the shield, what is wielded, then the rings, in that order. |
Examples:
from osrlib.core.items import Inventory, ItemInstance, MagicItemInstance
from osrlib.data import load_equipment
ring = MagicItemInstance(instance_id="magic-item-0001", template_id="ring_of_protection")
rope = ItemInstance(template=load_equipment().get("rope"))
inventory = Inventory(items=[rope], rings=[ring])
print([getattr(instance, "template_id", None) for instance in inventory.equipped_instances()])
# ['ring_of_protection']
magic_item
magic_item(instance_id: str) -> MagicItemInstance | None
Return the carried magic item with instance_id, or None.
Commands take the instance id of the magic item to drink, read, or take off, so this is the lookup for it. It searches the item list and every equipped slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance_id
|
str
|
The instance id, for example |
required |
Returns:
| Type | Description |
|---|---|
MagicItemInstance | None
|
The instance, or |
Examples:
carried_item
carried_item(item_id: str) -> ItemInstance | MagicItemInstance | None
Return the first instance of a catalog id the character is carrying, mundane or magic, or None.
Call this when you know what you want but not which copy: does anyone have a torch, does
this character still have arrows. It searches in
all_instances order: the item list, then
worn armour, the shield, what is wielded, and the rings. A mundane instance matches on
its template's id and a magic one on its template_id. Equipment ids and magic item
ids never collide, so an id matches only one of the two kinds.
A spent stack never matches. Only a magic instance can have a quantity of zero, like an emptied bundle of arrows +1, and it means the character has none left. So you can take a unit from whatever this returns.
Valuables never match either: a gem has no catalog id, only an instance id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_id
|
str
|
The catalog id to look for. It's an equipment id from
|
required |
Returns:
| Type | Description |
|---|---|
ItemInstance | MagicItemInstance | None
|
The instance, or |
Examples:
from osrlib.core.items import Inventory, ItemInstance
from osrlib.data import load_equipment
inventory = Inventory(items=[ItemInstance(template=load_equipment().get("torch"), quantity=6)])
carried = inventory.carried_item("torch")
assert carried is not None and carried.quantity == 6
assert inventory.carried_item("lantern") is None
ItemInstance
Bases: BaseModel
A stack of mundane items a character has.
purchase makes one. Construct one yourself to give a
character an item without charging for it, and add it to their
Inventory. Unlike a magic item, a mundane instance has
no instance id. Its template identifies it, so two stacks of the same item are
interchangeable.
instance_type
class-attribute
instance-attribute
instance_type: Literal['item'] = 'item'
Always "item".
template
instance-attribute
template: ItemTemplate
The item itself, one of the four equipment templates. See ItemTemplate. The
whole template is embedded rather than referenced by id, so an instance of an item an adventure bundled stays
readable without that adventure.
MagicArmourTypeTable
Bases: BaseModel
The Magic Armour Type table, which gives the mundane armour a generated suit of Armour +N is made of.
An Armour +N template has no mundane base item, so
instantiate_magic_item rolls this d8 to
pick one and records it on the instance's base_item_id. Roll it yourself with
base_for_roll only when you
are placing armour by hand and want the same distribution.
rows
class-attribute
instance-attribute
rows: tuple[ArmourTypeRow, ...] = Field(min_length=1)
The bands, in order, covering the whole d8. See ArmourTypeRow.
base_for_roll
Return the mundane armour a d8 roll makes a generated suit out of.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll
|
int
|
The d8 result, 1 to 8. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The mundane armour id, one of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the roll is outside 1 to 8. |
Examples:
MagicItemCatalog
Bases: BaseModel
The whole magic item list, with the tables that generate from it.
Call load_magic_items to get the compiled catalog. It's
frozen, and every call returns the same cached object. Look up an item by id with
get, and a type's generation table with
sub_table. Treasure generation in
osrlib.core.treasure loads this catalog itself, so you need it
only to read items, not to generate them.
Magic item ids never collide with equipment ids, so a single id refers to one thing across both catalogs. An adventure can't bundle magic item templates. It places the compiled ones.
sub_tables
instance-attribute
sub_tables: tuple[MagicSubTable, ...]
One generation table per type on the master Magic Item Type table. See
MagicSubTable.
armour_type
instance-attribute
armour_type: MagicArmourTypeTable
What a generated suit of enchanted armour is made of. See
MagicArmourTypeTable.
scroll_spell_levels
instance-attribute
scroll_spell_levels: ScrollSpellLevelTable
Which spell level each spell on a generated scroll is. See
ScrollSpellLevelTable.
sentient_swords
instance-attribute
sentient_swords: SentientSwordTables
The tables for rolling up a sentient sword. See SentientSwordTables.
get
get(item_id: str) -> MagicItemTemplate
Return the magic item template with item_id.
Use it to turn an id into an item: the template_id on a
MagicItemInstance (for which
magic_item_template is the shorthand), an id
an adventure places, or an id you're generating from. Lookup is a scan, so hoist it out
of a hot loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item_id
|
str
|
A magic item id from
|
required |
Returns:
| Type | Description |
|---|---|
MagicItemTemplate
|
The template. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no item has that id. |
Examples:
sub_table
sub_table(category: MagicItemType) -> MagicSubTable
Return the generation table for one type of the master Magic Item Type table.
Call it when you're rolling a type's table yourself. When you want a whole item rolled,
call generate_magic_item instead, which
rolls the master table, this one, and the item's details.
The master table's rod, staff, and wand row covers three catalog categories, and passing
ROD_STAFF_WAND returns the one table that produces all three.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
MagicItemType
|
The type on the master Magic Item Type table. See
|
required |
Returns:
| Type | Description |
|---|---|
MagicSubTable
|
The sub-table. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no sub-table covers that type. |
Examples:
MagicItemCategory
Bases: StrEnum
What kind of magic item a template is, in the magic item catalog.
Every MagicItemTemplate has one. The category
governs how the item is handled: what equip does with it,
whether treasure_weight_coins weighs it as
treasure, and whether generation rolls sentience for it.
These are the categories of the catalog, not the types of the random-generation table.
The table's rod, staff, and wand row covers three categories here. See
MagicItemType for the table's types and
MagicItemCatalog.sub_table for how one
maps to the other.
The lowercase values appear in the compiled magic item data.
ARMOUR
class-attribute
instance-attribute
Enchanted armour and shields. Worn in the armour or shield slot.
MISC
class-attribute
instance-attribute
Every magic item that fits no other category: cloaks, boots, bags, crystal balls.
ROD
class-attribute
instance-attribute
Rods. Wielded, with charges rolled when the rod is created.
STAFF
class-attribute
instance-attribute
Staves. Each one is also a mundane staff, wielded as a two-handed weapon. Most have charges, rolled when the staff is created.
WAND
class-attribute
instance-attribute
Wands. Wielded, with charges rolled when the wand is created, and usable only by arcane casters.
SCROLL
class-attribute
instance-attribute
Scrolls and treasure maps. Not equippable.
SWORD
class-attribute
instance-attribute
Enchanted swords, the only items that can be sentient.
MagicItemEffect
Bases: BaseModel
The part of a magic item's behavior the engine resolves for you.
An item whose page describes something the engine can execute has one of these. The rest
have their page text in the template's manual field, for you to narrate and
adjudicate yourself. kind selects which behavior runs, and the behavior reads the fields
it needs, so most fields are empty on most items.
Read kind to find out which behavior the engine runs for an item. Read modifiers to
show what a worn item grants, since
equipped_item_modifiers returns exactly
those for every equipped always-active item.
The kinds the compiled catalog uses are worn_modifiers, potion, damage_area,
condition_area, healing, save_or_die, on_hit_drain, striking, ward,
regeneration, light, giant_strength, and weakness.
kind
class-attribute
instance-attribute
Which behavior the engine runs for the item.
modifiers
class-attribute
instance-attribute
modifiers: tuple[ModifierSpec, ...] = ()
Stat modifiers the item grants. See ModifierSpec.
condition
class-attribute
instance-attribute
condition: str | None = None
The condition the item inflicts, for the behaviors that inflict one.
damage_dice
class-attribute
instance-attribute
damage_dice: str | None = None
The damage it deals, as a dice expression.
heal_dice
class-attribute
instance-attribute
heal_dice: str | None = None
The hit points it restores, as a dice expression.
element
class-attribute
instance-attribute
element: str | None = None
The damage element, for example "fire", for the target's immunity checks.
save_category
class-attribute
instance-attribute
save_category: str | None = None
Which saving throw column the target rolls against.
save_on
class-attribute
instance-attribute
save_on: Literal['negates', 'half'] | None = None
What a successful save does: "negates" the effect entirely, or "half" the damage.
shape
class-attribute
instance-attribute
shape: str | None = None
What kind of area an area effect covers, like "cone" or "sphere".
dimensions
class-attribute
instance-attribute
The area's measurements in feet, keyed by name.
range_feet
class-attribute
instance-attribute
range_feet: int | None = None
How far the effect reaches.
duration_unit
class-attribute
instance-attribute
duration_unit: str | None = None
The unit the duration counts in, for example "turns" or "rounds".
duration_amount
class-attribute
instance-attribute
duration_amount: int | None = None
A fixed duration, in duration_units.
duration_dice
class-attribute
instance-attribute
duration_dice: str | None = None
A rolled duration, as a dice expression, in duration_units.
MagicItemInstance
Bases: BaseModel
One magic item a character has, with everything that differs from copy to copy.
Templates are shared and frozen. This is the copy in play, and it's mutable. Treasure
generation makes them
(instantiate_magic_item and
generate_magic_item), an
Inventory contains them, and
magic_item_template gets you back to the
template behind one.
An instance starts unidentified, and a player-facing view shows it as an unknown item
until it's identified. In a session, the engine identifies it the first time a character
uses it: drinks the potion, swings the sword, or puts on the ring. A referee can also
identify it with IdentifyItem. The engine reveals a
cursed item's curse at the same moment. From then on the bearer can't take it off until the remove curse spell
lifts the curse, and unequip raises a ValueError whose
message includes items.curse.stuck.
instance_type
class-attribute
instance-attribute
instance_type: Literal['magic_item'] = 'magic_item'
Always "magic_item". This field distinguishes it from a mundane
ItemInstance when both are stored in one list.
instance_id
instance-attribute
instance_id: str
The id of this copy, for example "magic-item-0003", allocated by
IdAllocator. Commands that act on a magic item identify it by this, not by its
template id.
template_id
instance-attribute
template_id: str
Which item it is. Get its template with
magic_item_template. Every id is in
load_magic_items and in the magic item id
index.
charges_remaining
class-attribute
instance-attribute
charges_remaining: int | None = None
How many charges are left in a rod, staff, or wand, or None for an item that has no charges. Keep this out of
the player's view: in the tabletop rules a charge count can't be discovered.
quantity
class-attribute
instance-attribute
How many the stack contains, for enchanted ammunition. A stack at 0 is spent and no longer counts as carried.
identified
class-attribute
instance-attribute
identified: bool = False
True once the party knows what the item is. A player-facing view masks an unidentified item's name and properties.
cursed_revealed
class-attribute
instance-attribute
cursed_revealed: bool = False
True once the engine has revealed the curse. From then on the item can't be unequipped or given away until the remove curse spell lifts the curse, which sets this back to False.
base_item_id
class-attribute
instance-attribute
base_item_id: str | None = None
The mundane item underneath an enchanted weapon, arrow, suit of armour, or staff. Look it up with
load_equipment (ids listed in the equipment id
index). For generic enchanted armour, this
is what the Magic Armour Type roll chose.
sentience
class-attribute
instance-attribute
sentience: SwordSentience | None = None
The sword's mind, for a sentient sword. See SwordSentience. None on
everything else.
state
class-attribute
instance-attribute
State specific to this copy, keyed by name: the effects a worn item has attached, an energy-drain sword's remaining drains, a ring of wishes' remaining wishes, the day a staff of healing last healed each target, the spells left on a scroll.
MagicItemTemplate
Bases: BaseModel
A magic item, compiled from the generation tables and the per-item pages.
Get one from MagicItemCatalog.get, or from
magic_item_template when what you have is an
instance. Templates are frozen and shared. In play, each
copy is a MagicItemInstance, which
instantiate_magic_item creates from a template.
That function rolls the details that differ from copy to copy.
A cursed item's penalty is a negative bonus, so the arithmetic is the same as for a good
item. The cursed armour and cursed shield that set armour class to a fixed value use
ac_set instead.
id
instance-attribute
id: str
The catalog id, for example "potion_of_healing". Get every id from
load_magic_items, or see the magic item id
index.
category
instance-attribute
category: MagicItemCategory
What kind of item it is. See MagicItemCategory.
base_item_id
class-attribute
instance-attribute
base_item_id: str | None = None
The mundane equipment id the enchantment overlays, for an enchanted sword, weapon, ammunition, or shield, and
"staff" for every magic staff. Look it up with load_equipment (ids listed in the
equipment id index). None for everything
else, including generic enchanted armour, whose base is rolled for each copy on the Magic Armour Type table and
recorded on the instance's base_item_id.
attack_bonus
class-attribute
instance-attribute
attack_bonus: int = 0
What the item adds to an attack roll. Negative when cursed. The staves of wizardry and snakes add 1.
damage_bonus
class-attribute
instance-attribute
damage_bonus: int = 0
What it adds to damage. Negative when cursed.
ac_bonus
class-attribute
instance-attribute
ac_bonus: int = 0
What it adds to the wearer's armour class. Negative when cursed.
ac_set
class-attribute
instance-attribute
ac_set: int | None = None
The armour class the item forces, on the descending scale, for the cursed armour and shield whose pages print
AC 9 [10]. None on every other item.
ac_set_ascending
class-attribute
instance-attribute
ac_set_ascending: int | None = None
The same forced armour class on the ascending scale.
versus
class-attribute
instance-attribute
versus: tuple[VersusBonus, ...] = ()
Bonuses against particular enemies. See VersusBonus.
cursed
class-attribute
instance-attribute
cursed: bool = False
True when the item is cursed. In a session, the engine reveals the curse the first time a character uses the item. From then on the bearer can't take it off until the remove curse spell lifts the curse.
charges_dice
class-attribute
instance-attribute
charges_dice: str | None = None
How many charges are in a new copy, as a dice expression, for a rod, staff, or wand. None for an item with no
charges, like the staves of healing and snakes, whose pages say "Does not use charges".
quantity_dice
class-attribute
instance-attribute
quantity_dice: str | None = None
How many arrive at once, as a dice expression, for enchanted ammunition.
usable_by
class-attribute
instance-attribute
Who can use it. See UsableBy.
always_active
class-attribute
instance-attribute
always_active: bool = False
True when the item works while it's worn or wielded, with nothing to invoke.
effect
class-attribute
instance-attribute
effect: MagicItemEffect | None = None
What the engine resolves for the item. See MagicItemEffect. None for an
item whose behavior is left to you, which has manual prose instead.
params
class-attribute
instance-attribute
Per-item scalars, keyed by name, for behaviors that read them. On a staff, melee_class_ids lists the classes
that may wield it whatever their weapon policy says: the magic-user, on the staves of power, striking, and wizardry.
manual_powers is true on a staff that strikes and has other powers, which the session leaves to the referee in
manual: the staves of power and wizardry. A use of such a staff that strikes no group is one of those powers.
manual
class-attribute
instance-attribute
The item's page text, for the parts you adjudicate yourself. Show these lines to the referee.
weight_coins
class-attribute
instance-attribute
The weight of one item in coins, for the potions, scrolls, rods, staves, and wands that weigh as treasure. The
figure comes from the TreasureWeight rows. 0 on every other item: an
enchanted weapon or suit of armour weighs as its mundane base item (see
equipment_weight_coins), and the SRD gives rings and miscellaneous
items no weight.
hoard_recipe
class-attribute
instance-attribute
hoard_recipe: tuple[TreasureEntry, ...] = ()
The treasure a map leads to, as printed treasure entries. See
TreasureEntry. Empty on everything but a treasure map. Generate the hoard
with generate_treasure_entries.
curses
class-attribute
instance-attribute
curses: tuple[ScrollCurse, ...] = ()
The cursed scroll's example curses. See ScrollCurse. Empty on every other
item.
MagicSubTable
Bases: BaseModel
One magic item type's generation table, with everything that type can produce and the rolls that produce it.
There's one of these for each type of the master Magic Item Type table. Get the one
you want with
MagicItemCatalog.sub_table.
The rules print two columns, B for Basic play and X for Expert, and osrlib calls the
choice between them the tier. The B column is a small die whose faces reach only part
of the outcome list. The X column is a d% covering all of it. Roll on the table with
row_for_basic or
row_for_expert, depending on the
tier. Or let generate_magic_item pick the
type, roll the sub-table, and create the item.
category
instance-attribute
category: MagicItemType
The type on the master Magic Item Type table that this table generates. See
MagicItemType.
basic_die
class-attribute
instance-attribute
How many sides the B column's die has, for example 8 for a d8.
rows
class-attribute
instance-attribute
rows: tuple[MagicSubTableRow, ...] = Field(min_length=1)
The outcomes, in printed order. See MagicSubTableRow.
row_for_basic
row_for_basic(roll: int) -> MagicSubTableRow
Return the row a Basic-tier roll of the table's small die selects.
Call this when you're rolling a table by hand and the game is at the Basic tier. For
the Expert tier call
row_for_expert. Roll the die
yourself, from the treasure stream, so the draw is part of the reproducible sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll
|
int
|
The die result, 1 through |
required |
Returns:
| Type | Description |
|---|---|
MagicSubTableRow
|
The selected row. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no row has that face, which includes every roll outside the die's range. |
Examples:
row_for_expert
row_for_expert(roll: int) -> MagicSubTableRow
Return the row an Expert-tier d% roll selects.
The X column covers the whole d%, so every roll from 1 to 100 selects a row. For the
Basic tier call row_for_basic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll
|
int
|
The d% result, 1 to 100, with a rolled |
required |
Returns:
| Type | Description |
|---|---|
MagicSubTableRow
|
The selected row. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the roll is outside 1 to 100. |
Examples:
MagicSubTableRow
Bases: BaseModel
One outcome of a magic item generation sub-table, with the item it yields and the rolls that select it.
The rules print two probability columns for every generation table, B for Basic play and X for Expert, and osrlib calls the choice between them the tier. The two columns index the same list of outcomes independently, so a row can sit in the X column without appearing in the B column at all.
You rarely read a row yourself:
generate_magic_item rolls one and hands
the result to
instantiate_magic_item. Read rows when
you're showing a referee what a table can produce.
item_ids
class-attribute
instance-attribute
What the row yields, as ids you look up with load_magic_items (listed in
the magic item id index). One id
usually, two for the armour rows that come with a shield.
basic_value
class-attribute
instance-attribute
basic_value: int | None = None
The single face of the sub-table's small die that selects this row in the B column. None when the printed cell
is blank, which means the B column can't produce this row.
expert_min
class-attribute
instance-attribute
The lowest d% roll that selects this row in the X column.
expert_max
class-attribute
instance-attribute
The highest, with a printed 00 read as 100. The X bands are contiguous and cover the whole d%.
params
class-attribute
instance-attribute
Generation values that replace the template's for this row, keyed by name: the quantity dice a printed band gives
for arrows and bolts (quantity_dice), a fixed quantity for the B column (basic_quantity_fixed), and the wish
count for a ring of wishes (wish_count_dice).
instantiate_magic_item takes them as its params.
Material
Bases: StrEnum
What a weapon or piece of ammunition is made of, where the rules care.
Some monsters are hurt only by silver or magical weapons. The material field of
WeaponTemplate and
AmmunitionTemplate marks a mundane weapon as
silver, and the damage pipeline in osrlib.core.combat reads it
when it checks a target's immunities. The field defaults to STANDARD. The compiled
catalog uses SILVER for the silver dagger and silver-tipped arrows.
The values "standard" and "silver" appear in the compiled equipment data.
STANDARD
class-attribute
instance-attribute
Ordinary steel, wood, or stone, which doesn't hurt a monster that only silver or magic can hurt.
MissileRanges
Bases: BaseModel
A missile weapon's three range bands, near to far.
Attack resolution measures the distance to the target, finds the band it falls in, and
applies that band's modifier: +1 at short range, nothing at medium, −1 at long. Beyond
the long band the shot is out of range. A
WeaponTemplate or a
CombatFacet has one of these exactly when it has the
MISSILE quality of WeaponQuality. Building either
with one and not the other raises a pydantic ValidationError. The compiled combat facets
of holy water and burning oil have ranges and the missile quality. The torch's has neither.
RangeBand
Bases: BaseModel
One missile range band in feet, as the SRD prints it (5'–80').
Three of these make up a weapon's MissileRanges,
and the band a shot falls into sets its attack modifier. Bands come from the
compiled equipment data (load_equipment). Construct one
yourself only when you build a missile weapon template to bundle with an adventure.
Both bounds are inclusive. The engine rejects an attack at a distance past the long
band's maximum with combat.attack.out_of_range.
min_feet
class-attribute
instance-attribute
The band's nearest distance in feet, inclusive.
ScrollCurse
Bases: BaseModel
One of the cursed scroll's example curses.
The SRD lists example curses a cursed scroll can have and leaves the choice to the
referee. osrlib compiles them into the
curses field of the cursed scroll's template.
In a session, when a character reads the cursed scroll, the engine picks one of them at
random. The engine resolves the curses marked wired. The rest are prose for you to adjudicate.
prose
instance-attribute
prose: str
The curse as its page prints it. Show this to the referee or the player.
wired
class-attribute
instance-attribute
wired: bool = False
True when the engine resolves the curse itself. In the compiled catalog these are energy drain, which takes a level, and slow healing, under which natural healing needs two days of rest instead of one and healing magic restores half, rounded down. False means the curse is only prose, and you decide what happens.
ScrollSpellLevelRow
Bases: BaseModel
One row of the Random Scroll Spell Level table, with the rolls that select it and the spell level it gives.
The B column here is bands of a d6 rather than single faces, and its bounds are None
on the rows only the X column can reach.
basic_min
class-attribute
instance-attribute
basic_min: int | None = None
The lowest d6 result in this row's B band, or None when the row is Expert-only.
basic_max
class-attribute
instance-attribute
basic_max: int | None = None
The highest d6 result in the row's B band, or None when the row is Expert-only.
expert_min
class-attribute
instance-attribute
The lowest d% result in this row's X band.
expert_max
class-attribute
instance-attribute
The highest d% result in the row's X band.
arcane_level
class-attribute
instance-attribute
The spell level this row gives a magic-user scroll.
ScrollSpellLevelTable
Bases: BaseModel
The Random Scroll Spell Level table, which gives the level of each spell on a generated scroll.
instantiate_magic_item rolls this once
per spell on a scroll, then picks a spell of that level from the scroll's spell list,
cleric or magic-user.
Roll it yourself with
level_for_basic or
level_for_expert when you
are writing a scroll by hand.
rows
class-attribute
instance-attribute
rows: tuple[ScrollSpellLevelRow, ...] = Field(min_length=1)
The rows, in printed order. See ScrollSpellLevelRow.
level_for_basic
Return the spell level a Basic-tier d6 roll gives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll
|
int
|
The d6 result, 1 to 6. |
required |
divine
|
bool
|
True for a cleric scroll, False for a magic-user scroll. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The spell level. Pass it to
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the roll is outside 1 to 6. |
Examples:
level_for_expert
Return the spell level an Expert-tier d% roll gives.
The X column also reaches spell levels 4 and up, which the B column can't.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll
|
int
|
The d% result, 1 to 100. |
required |
divine
|
bool
|
True for a cleric scroll, False for a magic-user scroll. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The spell level. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the roll is outside 1 to 100. |
Examples:
SentientSwordTables
Bases: BaseModel
Every table that goes into rolling up a sentient sword.
instantiate_magic_item runs these for
you whenever it creates a sword, in the order the rules print them. First comes a
1-in-20 check for a sword with a special purpose, which is always sentient, with
intelligence 12 and ego 12. Any other sword has a 30% chance of sentience. A sentient
sword then rolls intelligence on 1d6+6, then communication, languages, alignment, and
powers, and finally ego on 1d12. The result is a
SwordSentience on the instance.
Read these tables directly when you're writing a sword by hand and want the printed odds.
communication
instance-attribute
communication: tuple[SwordCommunicationRow, ...]
How a sword of each intelligence communicates. See
SwordCommunicationRow.
languages
instance-attribute
languages: tuple[SwordTableBand, ...]
How many languages a speaking sword knows.
powers
instance-attribute
powers: tuple[SwordPowersRow, ...]
How many powers a sword of each intelligence has. See SwordPowersRow.
sensory_bands
instance-attribute
sensory_bands: tuple[SwordTableBand, ...]
Which sensory power a roll yields.
extraordinary_bands
instance-attribute
extraordinary_bands: tuple[SwordTableBand, ...]
Which extraordinary power a roll yields.
powers_catalog
instance-attribute
powers_catalog: tuple[SwordPower, ...]
Every power, with its text. See SwordPower.
special_purposes
instance-attribute
special_purposes: tuple[SwordTableBand, ...]
The purposes a special sword can be made for, like slaying a kind of creature.
special_purpose_prose
class-attribute
instance-attribute
special_purpose_prose: str = ''
The rule for the extra power a special sword brings to bear on its purpose. Show it to the referee.
alignment_touch_prose
class-attribute
instance-attribute
alignment_touch_prose: str = ''
The rule for the damage a sword deals to a bearer of the wrong alignment, which is also the only way to learn its alignment. Show it to the referee. The engine doesn't apply it.
power
power(power_id: str) -> SwordPower
Return the power with power_id.
Use it to turn the ids on a sword's
SwordSentience into names and text you can show.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
power_id
|
str
|
The power id, for example |
required |
Returns:
| Type | Description |
|---|---|
SwordPower
|
The power. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no power has that id. |
Examples:
SwordCommunicationRow
Bases: BaseModel
How a sentient sword of a given intelligence communicates, from the Communication table.
There's one row per intelligence score, in
SentientSwordTables.communication.
instantiate_magic_item reads the row for
the sword's intelligence and copies it onto the sword's
SwordSentience. Read the rows directly only to show
the table or to write a sword by hand.
int_score
class-attribute
instance-attribute
The sword's intelligence, 7 to 12.
reading
instance-attribute
reading: bool
True when the sword can read. In the compiled table, swords of intelligence 11 and 12 can.
communication
instance-attribute
communication: str
How it makes itself understood: "empathy" for a sword that only sends feelings, "speech" for one that talks.
osrlib rolls languages only for a speaking sword.
SwordControlResult
Bases: BaseModel
The totals and the winner of one contest of wills between a sentient sword and its wielder.
Returned by
sword_control_check. It contains the two
totals and who won. The check does nothing else: it emits no events, applies no conditions,
and changes neither party. What a sword in control makes its wielder do is the referee's to narrate.
sword_controls
instance-attribute
sword_controls: bool
True when the sword's total is higher and it takes charge. A tie goes to the wielder.
SwordPower
Bases: BaseModel
One power a sentient sword can have.
Each power is text for you to adjudicate. osrlib rolls which powers a sword has and
leaves what they do to the referee. Look one up by id with
SentientSwordTables.power, and show
prose to the referee.
id
instance-attribute
id: str
The power id, for example "detect_magic". This is what a sword's
SwordSentience records.
extraordinary
class-attribute
instance-attribute
extraordinary: bool = False
True for an extraordinary power, False for a sensory one. The two are rolled on separate tables.
duplicates_allowed
class-attribute
instance-attribute
duplicates_allowed: bool = False
True when rolling the same power twice means something, so the roll stands instead of being re-rolled.
SwordPowersRow
Bases: BaseModel
How many powers a sentient sword of a given intelligence has, from the Powers table.
There's one row per intelligence score, in
SentientSwordTables.powers.
instantiate_magic_item reads the row for
the sword's intelligence and rolls that many powers on the sensory and extraordinary
tables. Read the rows directly only to show the table or to write a sword by hand.
int_score
class-attribute
instance-attribute
The sword's intelligence, 7 to 12.
sensory
class-attribute
instance-attribute
How many sensory powers it gets, the ones that detect things.
SwordSentience
Bases: BaseModel
A sentient sword's mind, alignment, and powers.
instantiate_magic_item rolls it once when it creates the
sword, and it doesn't change after that. It's the sentience field of the sword's
MagicItemInstance. Most swords have none, and
the field is None for those. Pass the sword to
sword_control_check to find out whether it
takes charge of its wielder.
intelligence
class-attribute
instance-attribute
The sword's intelligence, 7 to 12. It sets how the sword communicates and how many powers it has.
ego
class-attribute
instance-attribute
The sword's ego, 1 to 12, or 12 for a sword of special purpose. In a contest of wills, the sword's total starts from its intelligence plus its ego.
communication
instance-attribute
communication: str
How it makes itself understood: "empathy" or "speech".
alignment
instance-attribute
alignment: str
The sword's alignment, as a lowercase name. A bearer of a different alignment takes damage for holding it, which the rules leave to the referee to apply.
languages
class-attribute
instance-attribute
How many languages a speaking sword knows. 0 for an empathic sword.
sensory_powers
class-attribute
instance-attribute
The ids of its sensory powers, the ones that detect things. Look them up with
SentientSwordTables.power.
extraordinary_powers
class-attribute
instance-attribute
The ids of its extraordinary powers, the ones that do things. Look them up the same way.
special_purpose
class-attribute
instance-attribute
special_purpose: str | None = None
What the sword was made to do, for example "chaotic_creatures", or None for a sword with no special purpose.
SwordTableBand
Bases: BaseModel
One band of a sentient sword roll table, whose result is either an outcome or an instruction to roll again.
The sentient sword roll tables share this structure: a roll range and a result. The result is usually
a value, like an alignment or the id of a power, and sometimes an instruction:
roll_twice on the language and both power tables, roll_thrice on an extraordinary
result of 00, and roll_extraordinary on a high sensory roll, which trades the
sensory power for an extraordinary one.
instantiate_magic_item resolves the
instructions for you when it rolls up a sword. Read the bands yourself only to show a
referee the table.
roll_min
class-attribute
instance-attribute
The lowest roll in this band.
roll_max
class-attribute
instance-attribute
The highest roll in this band.
TreasureWeight
Bases: BaseModel
What one unit of a kind of treasure weighs, from the SRD's encumbrance table.
Each row gives a weight in coins: coin and gem weigh 1 each, jewellery 10, and
potions, scrolls, rods, staves, and wands each have a separate figure. osrlib copies the
figures onto what they weigh. The magic item kinds are compiled into the weight_coins
of each MagicItemTemplate, and treasure
generation copies the gem and jewellery figures onto each
ValuableInstance it creates.
treasure_weight_coins reads those copies,
not these rows. The rows come with the equipment catalog
(load_equipment) rather than the treasure tables,
because the SRD prints them on its encumbrance page.
UsableBy
Bases: BaseModel
Which characters a magic item works for.
usable_by_class checks a class against this
model, and validate_equip applies it to rods, wands,
and miscellaneous items, rejecting with items.equip.not_usable.
Enchanted swords, weapons, and armour stay at the default all: their pages print "per
normal class restrictions", and those restrictions are the class's armour and weapon
policies, applied to the mundane item underneath rather than here. A magic staff's
usability decides who can use its powers. Who can wield it follows the class's weapon
policy for the mundane staff, as validate_equip says.
kind
class-attribute
instance-attribute
kind: Literal['all', 'classes', 'caster'] = 'all'
"all" for anything a character can use, "classes" to restrict to named classes, "caster" to restrict to
spell casters of a kind.
class_ids
class-attribute
instance-attribute
The classes that may use it, when kind is "classes", as ids from load_classes.
They're listed in the class id index. Empty
otherwise.
caster
class-attribute
instance-attribute
caster: Literal['arcane', 'divine', 'any'] | None = None
Which kind of caster may use it, when kind is "caster": "arcane" (magic-users and elves), "divine"
(clerics), or "any". None otherwise. Wands are arcane-only. Each staff follows the rule on its page.
ValuableInstance
Bases: BaseModel
One gem or piece of jewellery a character carries.
Treasure generation rolls the value once, when the piece is created, and it never
changes. generate_treasure returns these
alongside the coins. SellTreasure sells a piece
for exactly value_gp, with no haggling or appraisal. The SRD gives no rate at which a
town buys treasure, and selling at full value makes a piece's sale price equal to the
experience it's worth. If you want haggling or appraisal, add them yourself.
instance_type
class-attribute
instance-attribute
instance_type: Literal['valuable'] = 'valuable'
Always "valuable".
instance_id
instance-attribute
instance_id: str
The id of this piece, for example "valuable-0001", allocated by
IdAllocator.
name
class-attribute
instance-attribute
name: str = ''
A display name for the piece. Generation sets a plain one. When you place treasure by hand in an adventure, you can give it any name.
value_gp
class-attribute
instance-attribute
What it's worth in gold pieces, and what it pays when sold.
weight_coins
class-attribute
instance-attribute
The weight in coins, taken from the treasure encumbrance rows when the piece was generated. See
TreasureWeight.
VersusBonus
Bases: BaseModel
A magic weapon's bonus against particular enemies, as in +2 vs Lycanthropes.
When the target matches, this bonus replaces the item's ordinary attack and damage bonus rather than adding to it. Attack resolution reads the clause off the template. You read it to show a player what a weapon is good against.
The engine never matches a clause's printed label against a monster's name. Instead, categories
lists tags a monster template has, like undead or enchanted, and template_ids
lists compiled monster ids from load_monsters. A clause
matches a target whose template has any of the listed tags or ids. Characters have no
monster template, so a clause never matches a character.
label
class-attribute
instance-attribute
The clause as the item's page prints it, for example "+2 vs Lycanthropes". Show this to players. Don't parse
it.
bonus
instance-attribute
bonus: int
The attack and damage bonus that applies against a matching target, replacing the item's base bonus.
categories
class-attribute
instance-attribute
Monster category tags that match, for example ("undead",).
template_ids
class-attribute
instance-attribute
Monster template ids that match, from load_monsters (listed in
the monster id index). At least one of
categories and template_ids is non-empty.
WeaponQuality
Bases: StrEnum
What a weapon can do in combat, as the SRD's weapon table prints it.
Every WeaponTemplate and every gear
CombatFacet has a tuple of these, and attack
resolution in osrlib.core.combat reads them: they are what makes
a bow behave differently from a mace. Compiled equipment already has its qualities. You
set them yourself only when you build a weapon template to bundle with an adventure.
The lowercase values appear in the compiled equipment data and in saves.
BLUNT
class-attribute
instance-attribute
A crushing weapon rather than an edged one. Only an edged melee weapon kills a sleeping target outright with a single hit.
BRACE
class-attribute
instance-attribute
Damage doubles when the wielder sets the weapon against a charging enemy.
CHARGE
class-attribute
instance-attribute
Damage doubles when the wielder charges with it.
MISSILE
class-attribute
instance-attribute
Usable at range. A template with this quality also has MissileRanges, and
the range band sets the attack modifier.
RELOAD
class-attribute
instance-attribute
Can't fire in two rounds in a row. The engine rejects the second shot only when the weapon_reload flag of
Ruleset is on. With the flag off, this quality has no effect.
SLOW
class-attribute
instance-attribute
The wielder always acts after everyone not using a slow weapon, regardless of the initiative roll.
SPLASH
class-attribute
instance-attribute
Thrown to burst on the target. A damaging hit deals the same damage dice again at the start of the next round. Holy water and burning oil have this quality.
WeaponTemplate
Bases: BaseModel
A mundane weapon, from the SRD's weapon table.
One of the four kinds of equipment template. Get one from the compiled catalog with
EquipmentCatalog.get, then buy it with
purchase, which creates the
ItemInstance a character carries.
Templates are frozen and shared. Construct one yourself only to bundle a weapon of your
own in an Adventure.
item_type
class-attribute
instance-attribute
item_type: Literal['weapon'] = 'weapon'
Always "weapon". This field distinguishes the four template kinds when they are stored or loaded together.
id
instance-attribute
id: str
The catalog id, for example "sword". Unique across every equipment list. Get every id from
load_equipment, or see the equipment id
index.
cost_gp
class-attribute
instance-attribute
The listed price in gold pieces, for one weapon.
weight_coins
class-attribute
instance-attribute
The weight in coins. For a missile weapon this already includes its ammunition and quiver, which is why ammunition itself weighs nothing.
damage
instance-attribute
damage: str
The damage the weapon deals, as a dice expression, for example "1d8". Ignored when the variable_weapon_damage
flag of Ruleset is off, and then every weapon deals 1d6.
qualities
instance-attribute
qualities: tuple[WeaponQuality, ...]
What the weapon can do. See WeaponQuality.
missile_ranges
class-attribute
instance-attribute
missile_ranges: MissileRanges | None = None
The three range bands, present exactly when qualities includes the missile quality.
material
class-attribute
instance-attribute
What it's made of, for monsters that only silver or magic can hurt. Standard unless the weapon is silvered.
encounter_movement_rate
Return how far a character moves in one combat round, in feet.
The encounter rate is a third of the exploration rate, rounded down. It's the figure printed in parentheses on the movement tables, as in 120' (40'). osrlib doesn't store it, so compute it again from a fresh exploration rate whenever the load changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_rate_feet
|
int
|
The exploration movement rate, from
|
required |
Returns:
| Type | Description |
|---|---|
int
|
The rate in feet per round. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
equip
equip(inventory: Inventory, definition: ClassDefinition, instance: ItemInstance | MagicItemInstance) -> None
Move an item out of the item list and into use.
Call this to arm a character outside a session. In a session the
EquipItem command does this and records it. Check
first with validate_equip if you would rather have
a reason than an exception.
Where the item goes depends on what it is: body armour to the worn slot, a shield to the shield slot, rings to the ring slots, and everything else that can be equipped to the wielded list. That includes weapons, torches, wands, and other magic devices and miscellaneous magic items. Whatever was in the armour or shield slot goes back to the item list. The item leaves the item list, so it's in exactly one place afterwards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory. Mutated. |
required |
definition
|
ClassDefinition
|
The character's class definition, from
|
required |
instance
|
ItemInstance | MagicItemInstance
|
The item to equip. It must be in this inventory's item list. Equip what the character is carrying, not a template or a copy. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the item isn't in the item list, or the class can't equip it. Call
|
Examples:
from osrlib.core.items import CoinPurse, Inventory, equip, purchase
from osrlib.data import load_classes, load_equipment
inventory = Inventory(purse=CoinPurse(gp=50))
fighter = load_classes().get("fighter")
sword = purchase(inventory, load_equipment().get("sword"))
equip(inventory, fighter, sword)
print(len(inventory.items), [held.template.id for held in inventory.wielded])
# 0 ['sword']
equipment_weight_coins
Return the weight of a character's weapons, armour, and gear, in coins.
Detailed encumbrance adds this to
treasure_weight_coins. Weapons, armour, and
ammunition weigh their listed weights, times the number carried. Ammunition in the
built-in catalog weighs 0, because the OSE SRD includes ammunition in the missile
weapon's weight. Ammunition that an adventure bundles with a weight of its own counts
that weight. Gear has no per-item weights, so carrying any gear at all adds a flat
MISC_GEAR_WEIGHT_COINS and no more.
An enchanted weapon weighs what its mundane base item weighs. Enchanted armour or an
enchanted shield weighs half of what its base item weighs, rounded down, because the
rules make enchanted armour lighter than the mundane kind. The base item is the one in
the instance's base_item_id, or in the template's when the instance has none. A magic
staff has the mundane staff as its base, but it weighs as treasure, so it adds nothing here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory to weigh. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The equipment weight in coins. |
Examples:
A sword weighs 60 coins and chainmail 400. The rope is gear, so it adds a flat 80 coins, which is what any amount of gear weighs:
from osrlib.core.items import CoinPurse, Inventory, equipment_weight_coins, purchase
from osrlib.data import load_equipment
catalog = load_equipment()
inventory = Inventory(purse=CoinPurse(gp=100))
for item_id in ("sword", "chainmail", "rope"):
purchase(inventory, catalog.get(item_id))
print(equipment_weight_coins(inventory))
# 540
equipped_item_modifiers
equipped_item_modifiers(inventory: Inventory) -> list[ModifierSpec]
Return the stat modifiers a character's equipped magic items grant.
The combat functions in osrlib.core.combat already count these
modifiers in attack rolls, damage, and saving throws. Call this yourself to show what a
character's worn items grant, or when you resolve a roll of your own. An item
contributes only while it's equipped and only if its template's always_active is
True, so taking a ring off takes its bonus away with no bookkeeping. An item's bonus to
armour class isn't a modifier: it's the ac_bonus of the item's template.
This function computes item bonuses from the inventory each time you call it, instead of
storing them as effects. They stack freely with spell bonuses. The cap that
modifier_total applies to spell modifiers, which
counts only the largest bonus and the largest penalty, never applies to them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory to scan. |
required |
Returns:
| Type | Description |
|---|---|
list[ModifierSpec]
|
The modifiers, in equipped order: worn armour, shield, wielded, rings. Empty when no equipped item grants one. |
Examples:
from osrlib.core.items import Inventory, MagicItemInstance, equipped_item_modifiers
ring = MagicItemInstance(instance_id="magic-item-0001", template_id="ring_of_protection")
modifiers = equipped_item_modifiers(Inventory(rings=[ring]))
print([(modifier.kind, modifier.value) for modifier in modifiers])
# [('save_bonus', 1)]
magic_item_template
magic_item_template(instance: MagicItemInstance) -> MagicItemTemplate
Return the template behind a magic item instance.
It looks the instance's template_id up in the compiled catalog. Call it to get from the
copy a character carries to the item's name, category, bonuses, and text. When you have
an id rather than an instance, call
MagicItemCatalog.get on the catalog that
load_magic_items returns, which does the same lookup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
MagicItemInstance
|
The instance whose template to look up. |
required |
Returns:
| Type | Description |
|---|---|
MagicItemTemplate
|
The frozen template. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the instance refers to an item the catalog doesn't have. |
Examples:
movement_rate_feet
Return how far a character moves in one exploration turn, in feet.
A dungeon crawl uses this number: how far a party gets on a turn of careful
movement. Character.movement_rate is
the shorthand when you have a character rather than a bare inventory. Pass the result to
encounter_movement_rate for the rate
inside a fight, a third of this one.
What sets the rate depends on the encumbrance setting of
Ruleset:
none: alwaysBASE_MOVEMENT_FEET. Nothing is weighed and no load limit applies.basic: the armour being worn, andcarrying_treasure. Unarmoured, the rate is 120', or 90' when carrying treasure. Light armour gives 90' or 60', and heavy armour 60' or 30'.detailed: the weight carried. The rate is 120' up to 400 coins, 90' up to 600, 60' up to 800, and 30' up to the maximum load. Each limit includes its own value. Worn gauntlets of ogre power add 1,000 coins to every limit and to the maximum load. So the wearer moves at 120' up to 1,400 coins.
Under basic and detailed, a character carrying more than the maximum load can't move
at all. The maximum load is MAX_LOAD_COINS, plus
the gauntlets' bonus under detailed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory to weigh. |
required |
ruleset
|
Ruleset
|
The ruleset whose |
required |
carrying_treasure
|
bool
|
Whether the character is carrying a significant amount of treasure, under basic encumbrance. The tabletop rules leave "significant" to the referee, and so does osrlib: you set this, and osrlib has no threshold for it. Ignored under the other two modes. |
False
|
Returns:
| Type | Description |
|---|---|
int
|
The movement rate in feet per turn: 120, 90, 60, 30, or 0. |
Examples:
from osrlib.core.items import Inventory, ItemInstance, movement_rate_feet
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_equipment
plate = ItemInstance(template=load_equipment().get("plate_mail"))
inventory = Inventory(worn_armour=plate)
print(
movement_rate_feet(inventory, Ruleset()),
movement_rate_feet(inventory, Ruleset(), carrying_treasure=True),
)
# 60 30
purchase
purchase(inventory: Inventory, template: ItemTemplate, lots: int = 1) -> ItemInstance
Buy lots of an item, pay for it out of the purse, and add it to the inventory.
Call this to buy equipment for a character outside a session. In a session the
PurchaseEquipment command does this and
records it. Check first with
validate_purchase if you would rather have a
reason than an exception.
A purchase lot is what one purchase at the item's listed price delivers. Gear and
ammunition come in lots of the size the catalog prints, so one purchase of torches costs
1 gp and yields six torches. Weapons and armour have no lot size, so one lot is one
item. lots multiplies both the price and what you get: two lots of torches cost 2 gp
and yield twelve torches, in one stack.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The buyer's inventory. Mutated: the purse is charged and the new stack is appended to the item list. |
required |
template
|
ItemTemplate
|
The item to buy, from
|
required |
lots
|
int
|
How many purchase lots. Positive. |
1
|
Returns:
| Type | Description |
|---|---|
ItemInstance
|
The new stack, which is also now in the inventory's item list. Pass it to
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
sword_control_check
sword_control_check(character: Character, sword: MagicItemInstance, *, stream: RngStream) -> SwordControlResult
Resolve one contest of wills between a sentient sword and the character holding it.
A sentient sword can try to take charge of its wielder. This runs that contest and reports who won. It changes nothing, because what a controlling sword makes its wielder do is a referee's call. The crawl never calls this, so you decide when a sword tries to take charge, and you narrate the result.
The sword's will is its intelligence plus its ego, plus 1 for each extraordinary power, plus 1d10 when wielder and sword are of different alignments. The wielder's will is strength plus wisdom, less 1d4 when they are hurt at all and 2d4 when they are below half their hit points. The sword takes charge when its total is higher than the wielder's. A tie goes to the wielder.
The wielder's strength is
Character.effective_strength, so a
wielder who wears gauntlets of ogre power adds 18 for it, and one under the curse of a ring
of weakness adds 3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The wielder. It must be a |
required |
sword
|
MagicItemInstance
|
The sword, which must have a
|
required |
stream
|
RngStream
|
The RNG stream the situational dice come from. Pass a session stream so the draws replay. Which stream is yours to choose. |
required |
Returns:
| Type | Description |
|---|---|
SwordControlResult
|
The two totals and who won. See
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sword isn't sentient. |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.items import MagicItemInstance, SwordSentience, sword_control_check
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
streams = RngStreams(master_seed=7)
wielder = create_character(
name="Aleran",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=streams.get(CHARACTER_CREATION_STREAM),
).character
sentience = SwordSentience(intelligence=12, ego=12, communication="speech", reading=True, alignment="chaotic")
sword = MagicItemInstance(
instance_id="magic-item-0001", template_id="sword_plus_1", base_item_id="sword", sentience=sentience
)
result = sword_control_check(wielder, sword, stream=streams.get("treasure"))
print(result.sword_will, result.wielder_will, result.sword_controls)
# 25 23 True
tracked_weight_coins
tracked_weight_coins(inventory: Inventory, mode: EncumbranceMode) -> int
Return the weight the encumbrance rules in play count, in coins.
Call this instead of the two weighing functions, because the answer depends on
the encumbrance setting of Ruleset. This is the
weight movement_rate_feet compares against
MAX_LOAD_COINS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory to weigh. |
required |
mode
|
EncumbranceMode
|
The encumbrance mode in play, the |
required |
Returns:
| Type | Description |
|---|---|
int
|
0 when nothing is tracked, the treasure weight under basic encumbrance, and treasure plus equipment under detailed. |
Examples:
treasure_weight_coins
Return the weight of the treasure a character is carrying, in coins.
This is the figure basic encumbrance tracks: coins, gems, jewellery, and the magic items the encumbrance table weighs as treasure, which are potions, scrolls, rods, staves, and wands. Every coin weighs 1, whatever its metal.
A stack of those magic items weighs its template's weight_coins times its quantity, so
a spent stack, at quantity 0, weighs nothing. Rings and miscellaneous magic items weigh
nothing, because the OSE SRD gives them no weight. Enchanted weapons and armour count as
equipment, like the mundane kind, rather than as treasure. That way basic encumbrance
measures what the rules mean by it: how much loot is being hauled out.
A character who has a bag of holding keeps their treasure in it. The bag takes up to 10,000 coins of weight, and a bag with anything in it weighs 600 coins, the weight the SRD gives for a full bag. Treasure past the bag's capacity weighs what it weighs. With two bags, the character fills one before starting the next, so 15,000 coins weigh 1,200. The adaptations register records this ruling.
Call tracked_weight_coins instead when you
want whatever the ruleset in play tracks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory to weigh. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The treasure weight in coins. |
Examples:
The 290 gold pieces left after you buy a sword count as treasure. The sword doesn't:
from osrlib.core.items import CoinPurse, Inventory, purchase, treasure_weight_coins
from osrlib.data import load_equipment
inventory = Inventory(purse=CoinPurse(gp=300))
purchase(inventory, load_equipment().get("sword"))
print(treasure_weight_coins(inventory))
# 290
With a bag of holding, 5,000 gold pieces weigh what the full bag weighs:
unequip
unequip(inventory: Inventory, instance: ItemInstance | MagicItemInstance) -> None
Take an item out of use and put it back in the item list.
The reverse of equip. In a session the
UnequipItem command does this and records it.
Check first with validate_unequip if you would
rather have a reason than an exception, since a revealed cursed item can't be taken off
at all.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory. Mutated. |
required |
instance
|
ItemInstance | MagicItemInstance
|
The equipped item, the object itself, from whichever slot it's in. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the item isn't equipped in this inventory, whatever curse it has, or if
it's equipped and its curse has been revealed. The message for a revealed curse
includes |
Examples:
from osrlib.core.items import CoinPurse, Inventory, equip, purchase, unequip
from osrlib.data import load_classes, load_equipment
inventory = Inventory(purse=CoinPurse(gp=50))
sword = purchase(inventory, load_equipment().get("sword"))
equip(inventory, load_classes().get("fighter"), sword)
unequip(inventory, sword)
print(len(inventory.wielded), [held.template.id for held in inventory.items])
# 0 ['sword']
usable_by_class
usable_by_class(template: MagicItemTemplate, definition: ClassDefinition) -> bool
Return whether a character of this class can use a magic item.
The rules restrict some items to particular classes or to spell casters, and this function
checks a class against those restrictions.
validate_equip applies it to rods, wands, and
miscellaneous items. A session applies it when a character uses a staff's powers. Call it
directly when you decide which magic items to offer a player.
Enchanted swords, weapons, and armour aren't restricted here: their pages defer to the class's ordinary armour and weapon policies, which apply to the mundane item underneath. Neither is wielding a magic staff, which follows the weapon policy for the mundane staff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
MagicItemTemplate
|
The magic item template. |
required |
definition
|
ClassDefinition
|
The character's class definition, from
|
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when the class may use the item. |
Examples:
validate_equip
validate_equip(
definition: ClassDefinition, instance: ItemInstance | MagicItemInstance, inventory: Inventory | None = None
) -> list[Rejection]
Check whether a character of this class can equip an item.
The check half of equip, which raises where this reports.
Call it to decide what to offer a player: which weapons a magic-user can pick
up, why a cleric can't draw the sword the party just found.
What it enforces:
- The class's armour policy: whether armour is allowed at all, and whether this suit is, and whether shields are.
- The class's weapon policy, which covers the weapons list only. Gear with a combat use (torch, holy water, burning oil) is exempt and always equippable, so a magic-user can throw oil. That exemption is an adaptation, a reading osrlib chooses where the rules are unclear. Nobody can equip gear without a combat use, or ammunition.
- Two-handed weapons and shields, which can't be used together. Whichever of the pair
comes second is rejected, so this check reads what is already equipped: pass
inventorywhenever you have one. - For magic items: enchanted arms and magic staves resolve through the policies of the
mundane item underneath, rings against the two-ring cap, and rods, wands, and
miscellaneous items against the usability of the item. See
usable_by_class. Potions and scrolls aren't equipment. - A magic staff is a mundane staff underneath, so a class that may wield a staff wields
every magic staff, whoever may use its powers. A class that a staff's
melee_class_idsparam lists wields that staff whatever its weapon policy says. In the built-in catalog that's the magic-user, who may use only daggers otherwise, and the staves of power, striking, and wizardry, because the OSE SRD says a magic-user can "use the staff of power, staff of striking, and staff of wizardry in melee". A staff is two-handed either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The character's class definition, from
|
required |
instance
|
ItemInstance | MagicItemInstance
|
The item to equip. |
required |
inventory
|
Inventory | None
|
The inventory whose equipped items the check reads, for the rule against a two-handed weapon with a shield and for the ring cap. Leave it out only when there's no inventory yet. Without it, neither check runs. |
None
|
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
The reasons it can't be equipped, as
|
Examples:
from osrlib.core.items import ItemInstance, validate_equip
from osrlib.data import load_classes, load_equipment
catalog = load_equipment()
cleric = load_classes().get("cleric")
print([rejection.code for rejection in validate_equip(cleric, ItemInstance(template=catalog.get("sword")))])
# ['items.equip.weapon_not_allowed']
print([rejection.code for rejection in validate_equip(cleric, ItemInstance(template=catalog.get("mace")))])
# []
validate_purchase
validate_purchase(purse: CoinPurse, template: ItemTemplate, lots: int = 1) -> list[Rejection]
Check whether a character can afford to buy lots of an item.
The check half of purchase, which raises where this
reports. Call this when you want a reason to show a player rather than an exception:
a shop screen that greys out what the party can't afford, or a command that rejects.
A purchase lot is what one purchase at the item's listed price delivers. See
purchase for what a lot buys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purse
|
CoinPurse
|
The buyer's purse. |
required |
template
|
ItemTemplate
|
The item to buy. |
required |
lots
|
int
|
How many purchase lots. Positive. |
1
|
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
The reasons the purchase can't go ahead, as
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
validate_unequip
validate_unequip(inventory: Inventory, instance: ItemInstance | MagicItemInstance) -> list[Rejection]
Check whether an equipped item can be taken off.
The check half of unequip, which raises where this
reports. There's one reason it can fail: a cursed item whose curse is revealed
stays on its bearer until the remove curse spell lifts the curse. Every cursed item's
page in the SRD prints that rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
Inventory
|
The inventory that contains the item. |
required |
instance
|
ItemInstance | MagicItemInstance
|
The equipped item, the object itself in one of the inventory's slots. |
required |
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
The reasons it can't come off, as
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the item isn't equipped in this inventory, whatever curse it has. Only an equipped item can be taken off, so asking about any other item is a mistake in the call, not a move the rules refuse. |
Examples:
from osrlib.core.items import Inventory, MagicItemInstance, validate_unequip
ring = MagicItemInstance(instance_id="magic-item-0001", template_id="ring_of_weakness", cursed_revealed=True)
inventory = Inventory(rings=[ring])
print([rejection.code for rejection in validate_unequip(inventory, ring)])
# ['items.curse.stuck']