osrlib.core.classes
Character classes, experience and levels, and the skill checks that depend on a character's class.
A character's class is what they are trained as, like a fighter, a cleric, or a thief. In B/X, the
dwarf, the elf, and the halfling are classes too. load_classes
returns the classes osrlib includes, compiled from the OSE SRD's class pages, as frozen
ClassDefinition models. Look one up by id with
ClassCatalog.get. For the ids, iterate
ClassCatalog.classes or see
the class id index. A character stores only the
class id, and its definition property returns the definition.
A definition is shared by every character of the class, and play never changes it. It contains the
minimum ability scores, the prime requisites, the experience-modifier tiers, the armour and weapon
rules, the class abilities as tags that the rules functions read, and a progression row for each
level. A progression row contains the experience points needed to reach the level, the hit dice,
THAC0, the saving throws, and the spell slots. A character stores none of these values. Its
properties read them from the row for the current level, which
ClassDefinition.row returns, so when a character
gains or loses a level, only the level changes.
The functions here, in the order you usually need them:
apply_xpawards experience points. It applies the class's experience modifier and levels the character up when the total reaches the next level. It's the advancement function you usually call.level_upraises a character one level and rolls the hit points for it. Call it to grant a level directly.drain_levelstakes levels away, as the touch of a wight does.xp_modifier_pctandlevel_titlereturn the experience modifier and the level title to show on a character sheet.thief_skill_checkrolls one of a thief's skills, like climbing a wall or picking a lock.detection_chancereturns a character's chance in 6 at a search, like listening at a door, anddetection_checkrolls against it.
To create a character, see osrlib.core.character.
Typical usage:
from osrlib.core.alignment import Alignment
from osrlib.core.character import ADVANCEMENT_STREAM, CHARACTER_CREATION_STREAM, create_character
from osrlib.core.classes import apply_xp, level_title
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
streams = RngStreams(master_seed=2)
fighter = load_classes().get("fighter")
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=streams.get(CHARACTER_CREATION_STREAM),
).character
result = apply_xp(character, fighter, 2500, streams.get(ADVANCEMENT_STREAM))
print(result.level_before, result.level_after, character.max_hp)
# 1 2 10
print(level_title(fighter, character.level), character.thac0, character.saves.death)
# Warrior 19 12
PERCENTILE_THIEF_SKILLS
module-attribute
PERCENTILE_THIEF_SKILLS = (
"climb_sheer_surfaces",
"find_remove_treasure_traps",
"hide_in_shadows",
"move_silently",
"open_locks",
"pick_pockets",
)
The names of the thief skills rolled on percentile dice, like "open_locks".
Pass any of these as the skill argument of
thief_skill_check, which rolls d% and succeeds on a
result equal to or under the chance for the thief's level. The thief's other skill,
"hear_noise", isn't here, because it's a chance in 6 rolled on 1d6. thief_skill_check accepts
it too.
Each name is also a field of ThiefSkillRow. To show a
thief's percentile skills, iterate this tuple and read each chance off the row with getattr.
ArmourPolicy
Bases: BaseModel
Which armour and shields a class may use.
Read it from ClassDefinition.armour.
validate_equip checks a character's armour and shield
against it. Among the built-in classes, the magic-user wears no armour, the thief wears leather
only, and the other classes may wear any armour. Frozen.
kind
instance-attribute
kind: ArmourPolicyKind
Which armour the class may wear. See ArmourPolicyKind.
shields_allowed
instance-attribute
shields_allowed: bool
Whether the class may use a shield. It must be False when kind is "none".
ArmourPolicyKind
Bases: StrEnum
Which armour a class may wear.
Read it from ArmourPolicy.kind.
validate_equip checks it when a character puts armour
on. The values are the strings "any", "leather_only", and "none".
ANY
class-attribute
instance-attribute
Any armour. The cleric, dwarf, elf, fighter, and halfling may wear any armour.
LEATHER_ONLY
class-attribute
instance-attribute
Leather armour only, which is the thief's rule. The thief may not use a shield either.
ClassAbility
Bases: BaseModel
One thing a class can do, like a dwarf's infravision: a tag the rules functions match, its numbers, and its text.
Read a class's abilities from
ClassDefinition.abilities. The combat,
magic, and exploration functions look for the tags they recognize and read the numbers from
params. They ignore a tag they don't recognize. Frozen.
An ability osrlib doesn't apply has manual set. Show its prose to the referee, who applies
it.
tag
instance-attribute
tag: str
The identifier the rules functions match, like "infravision", "detect_secret_doors", or "back_stab".
prose
instance-attribute
prose: str
The SRD's description of the ability, to show a player or the referee.
manual
class-attribute
instance-attribute
manual: bool = False
True when osrlib doesn't apply this ability, and the referee applies it from prose.
params
class-attribute
instance-attribute
The values the rules functions read, like {"range_feet": 60} for infravision or {"chance_in_six": 2} for a
detection ability. Empty when the ability has none.
A divine_magic or arcane_magic ability has a spell_list, the id of the spell list the class casts from, like
"magic_user". ClassDefinition refuses a casting ability without one.
ClassCatalog
Bases: BaseModel
A set of class definitions, like the built-in classes that load_classes returns.
Look a class up by id with get, or iterate classes
to list the classes a player can choose from. load_classes loads its catalog once and caches
it, so calling it again costs almost nothing. Frozen.
classes
instance-attribute
classes: tuple[ClassDefinition, ...]
The class definitions. The built-in catalog lists them in alphabetical order of id. No two have the same id.
get
get(class_id: str) -> ClassDefinition
Return the class with class_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_id
|
str
|
The id to look up, like |
required |
Returns:
| Type | Description |
|---|---|
ClassDefinition
|
The class definition. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no class has that id. The message includes the id you passed. |
Examples:
ClassDefinition
Bases: BaseModel
A character class, like the fighter or the elf: its rules, and its values at every level.
Get one from load_classes().get(class_id). For the ids, iterate
load_classes().classes or see the class id
index. A
Character stores only the class id, and
Character.definition returns the definition for it. Pass the
definition to the functions in this module that take one, like apply_xp.
A definition is frozen and shared by every character of the class. What changes in play, like
the level and the hit points, is stored on the character. The built-in definitions are compiled
from the SRD's class pages. To write a class of your own, build a ClassDefinition with
model_validate, which checks it with the same rules as the built-in classes. One of those rules
is that a divine_magic or arcane_magic ability has a spell_list param, so
caster_profile always finds the list a casting class uses.
name
instance-attribute
name: str
The class's name as the SRD prints it, like "Magic-User", for display.
race
class-attribute
instance-attribute
The race of the class's characters, as a lowercase identifier, like "human" or "dwarf".
Creation copies it onto the character. No rules function reads it. What a race can do comes from abilities.
requirements
class-attribute
instance-attribute
The lowest ability score a character needs in each listed ability to take this class.
validate_class_choice checks them. Empty for the human classes.
The dwarf, the elf, and the halfling each require a 9 in one or two abilities.
prime_requisites
instance-attribute
prime_requisites: tuple[AbilityScore, ...]
The abilities the class depends on most. There's one for most classes, and two for the elf and the halfling.
The ability-score adjustment at creation can raise only these, and can't lower them. The experience modifier in
xp_tiers usually depends on them.
xp_tiers
instance-attribute
The experience-modifier tiers, highest percentage first.
xp_modifier_pct reads them.
hit_die
instance-attribute
hit_die: int
The number of sides on the class's hit die. It's 4, 6, or 8 for the built-in classes.
max_level
class-attribute
instance-attribute
The highest level a character of this class can reach. It's 14 for the human classes, 12 for the dwarf, 10 for the elf, and 8 for the halfling.
armour
instance-attribute
armour: ArmourPolicy
Which armour and shields the class may use. See ArmourPolicy.
weapons
instance-attribute
weapons: WeaponPolicy
Which weapons the class may wield. See WeaponPolicy.
languages
instance-attribute
The ids of the languages every character of this class speaks, starting with "common".
A character's full list, with the alignment tongue and any extra languages, is
Character.languages.
may_not_lower
class-attribute
instance-attribute
may_not_lower: tuple[AbilityScore, ...] = ()
Abilities the ability-score adjustment at creation can't lower, besides the prime requisites. The thief's is STR.
abilities
class-attribute
instance-attribute
abilities: tuple[ClassAbility, ...] = ()
What the class can do, as tags the rules functions read.
See ClassAbility.
thief_skills
class-attribute
instance-attribute
thief_skills: tuple[ThiefSkillRow, ...] = ()
The thief's skill chances, one row per level from 1 to max_level. Empty for every built-in class but the thief.
See ThiefSkillRow.
level_titles
class-attribute
instance-attribute
The title of a character at each level, starting with level 1, like "Veteran" for a first-level fighter.
The SRD prints titles only up to name level, so this can be shorter than progression. Call
level_title to read one, which returns None for a level past the end.
progression
instance-attribute
progression: tuple[ProgressionRow, ...]
One progression row for each level from 1 to max_level, in order. Read one with
row, which checks the level.
overrides_applied
class-attribute
instance-attribute
The fields osrlib corrected when it compiled this class from the SRD, like "xp_tiers". Empty when none were.
Read it when you check osrlib's data against the SRD. No rules function reads it.
row
row(level: int) -> ProgressionRow
Return the class's progression row for level.
A character's THAC0, attack bonus, saving throws, hit dice, and spell slots come from the
row for their current level. When you have a character, read its properties instead, like
Character.thac0 and
Character.saves, which call this for you. Call
it yourself to look at another level, like the experience a character needs for the next level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int
|
The level to read, from 1 to |
required |
Returns:
| Type | Description |
|---|---|
ProgressionRow
|
The progression row for that level. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
DetectionResult
Bases: BaseModel
The result of a chance-in-6 check, like listening at a door or searching for a secret door.
detection_check returns one. Frozen.
DrainResult
Bases: BaseModel
What an energy drain took from a character.
drain_levels returns one. Its events describe the
drain, for you to show. Frozen.
levels_lost
instance-attribute
levels_lost: int
How many levels the drain took. When the drain killed the character, the last level, the one that killed them, counts too.
new_level
class-attribute
instance-attribute
The character's level after the drain, or 0 when the drain killed them.
A character killed by a drain still has a level of 1, because the model doesn't allow 0.
hp_rolls
class-attribute
instance-attribute
The hit die results thrown for the levels lost, before the CON modifier, in the order thrown.
No die is thrown for a lost level that added no hit die, so this can be shorter than levels_lost, or empty.
hp_lost
instance-attribute
hp_lost: int
The hit points the drain rolls to take, from both maximum and current hit points.
Neither total drops below 1 while the character has a level left, so the totals can fall by less than this.
The drain event in events has its own hp_lost, which is how far the maximum actually fell.
xp_after
class-attribute
instance-attribute
xp_after: int | None = None
The character's experience points after the drain, or None when the drain killed them.
slain
class-attribute
instance-attribute
slain: bool = False
True when the drain took the character's last level and killed them.
events
class-attribute
instance-attribute
The events that describe the drain, in the order they happen.
The first is a LevelDrainedEvent. When the character survives, a
HitPointsReportedEvent follows, then a
SpellForgottenEvent for each memorized spell that no longer fits. When
the drain kills the character, the death events follow instead.
HitDice
Bases: BaseModel
A class's hit dice at one level: how many, of what size, and any flat bonus.
Read it off ProgressionRow.hit_dice.
level_up and
drain_levels compare the hit dice of two neighbouring
levels. When count rises from one level to the next, the level gained or lost is worth a
rolled die. When it doesn't, the level is worth the difference between the two bonus values.
Frozen.
A class stops gaining dice at name level, the level at which a character may build a
stronghold. After that it gains a flat number of hit points per level. The SRD writes those
levels with an asterisk, as in 9d8+2*, to show that the CON modifier no longer applies.
count
class-attribute
instance-attribute
The number of hit dice the class has at this level. At least 1.
die
instance-attribute
die: int
The number of sides on each die, which is the class's hit die: 4 for the magic-user and thief, 6 for the cleric, elf, and halfling, and 8 for the dwarf and fighter.
bonus
class-attribute
instance-attribute
The flat hit points added to the dice, which is how a character gains hit points past name level. At least 0.
con_applies
class-attribute
instance-attribute
con_applies: bool = True
Whether the CON modifier applies to a die gained at this level.
It's False at the levels the SRD writes with an asterisk, as in 9d8+2*. Whether a die is rolled at all is a
separate question, which depends on whether count rises from the level below.
LevelUpResult
Bases: BaseModel
What a character gained with a new level.
level_up returns one, and
XpAwardResult.level_up contains one when an
experience award raised the level. Show it to tell a player what the new level gave them.
Frozen.
hp_roll
instance-attribute
hp_roll: int | None
The hit die result before the CON modifier, or None when the new level adds no hit die.
With no hit die, the gain is the difference between the bonus values of the two levels' hit dice.
hp_gained
instance-attribute
hp_gained: int
The hit points added to both maximum and current hit points.
When a die was rolled, it's at least 1, however low the die and the CON modifier.
con_applied
instance-attribute
con_applied: bool
Whether the CON modifier counted toward the gain.
It's the con_applies value of the new level's hit dice when a die was rolled, and False when none was.
ProgressionRow
Bases: BaseModel
A class's values at one level: the experience a character needs to reach the level, and what the level grants.
Get one from ClassDefinition.row. A character's
THAC0, attack bonus, saving throws, and spell slots come from the row for their current level,
read each time rather than stored. That's why level_up and
drain_levels need to change only the level. Frozen.
level
class-attribute
instance-attribute
The level this row describes, from 1.
xp
class-attribute
instance-attribute
The total experience points a character needs to reach this level. It's 0 at level 1, and rises each level.
thac0
class-attribute
instance-attribute
The d20 roll needed to hit armour class 0, for descending armour class.
attack_bonus
class-attribute
instance-attribute
The bonus added to an attack roll, for ascending armour class. It describes the same attack as thac0.
saves
instance-attribute
saves: SavingThrows
The saving throw targets at this level. See SavingThrows.
spell_slots
class-attribute
instance-attribute
How many spells of each spell level the class can memorize at this level.
The first entry is for first-level spells, the second for second-level spells, and so on. An entry is 0 when the class can't yet memorize spells of that level, as with a first-level cleric. Empty for a class that casts no spells.
SavingThrows
Bases: BaseModel
The five saving throw targets, one for each kind of danger.
A save succeeds on a 1d20 roll equal to or higher than the target for the danger, so a lower
target is better. Read a character's current targets from
Character.saves and a monster's from
MonsterInstance.saves.
saving_throw rolls a save against them for you. Frozen.
death
class-attribute
instance-attribute
The target against death rays and poison.
wands
class-attribute
instance-attribute
The target against magic wands.
paralysis
class-attribute
instance-attribute
The target against paralysis and being turned to stone.
breath
class-attribute
instance-attribute
The target against a breath attack, like a dragon's.
SkillCheckResult
Bases: BaseModel
The result of a thief skill check.
thief_skill_check returns one. Frozen.
roll
instance-attribute
roll: int
The die result: from 1 to 100 for a percentile skill, or from 1 to 6 for hear_noise.
chance
instance-attribute
chance: int
The number the roll had to equal or come under, after the modifier_pct you passed.
For pick_pockets, it's at most 99, so a theft can always fail.
passed
instance-attribute
passed: bool
Whether the check succeeded: roll is equal to or under chance.
noticed
class-attribute
instance-attribute
noticed: bool | None = None
For pick_pockets only, True when the victim noticed the attempt, which happens when roll is more than twice
chance. None for every other skill. What happens to a thief who is noticed is up to you or the referee.
ThiefSkillRow
Bases: BaseModel
A thief's skill chances at one level.
Read the row for a thief's level from
ClassDefinition.thief_skills, or let
thief_skill_check find it and roll for you. Frozen.
Every skill except hear_noise is a percentage, rolled on d%, and succeeds on a roll equal to
or under the chance. hear_noise is a chance in 6, rolled on 1d6, so osrlib stores the SRD's
"1-2" as 2. pick_pockets is above 100 at high levels. thief_skill_check lowers the chance
to 99, so a theft can always fail.
level
class-attribute
instance-attribute
The thief level this row describes.
climb_sheer_surfaces
class-attribute
instance-attribute
The percent chance to climb a sheer surface. It's 87 at first level.
find_remove_treasure_traps
class-attribute
instance-attribute
The percent chance to find or remove a trap on a treasure container, like a chest.
Spotting a trap in a room is a different check, made with
detection_chance.
hear_noise
class-attribute
instance-attribute
The chance in 6 of hearing noise through a door, rolled on 1d6.
hide_in_shadows
class-attribute
instance-attribute
The percent chance to stay unseen while keeping still in shadow.
move_silently
class-attribute
instance-attribute
The percent chance to move without being heard.
open_locks
class-attribute
instance-attribute
The percent chance to pick a lock. In a session, the engine rejects a
PickLock command unless the thief carries thieves' tools.
WeaponPolicy
Bases: BaseModel
Which weapons a class may wield.
Read it from ClassDefinition.weapons.
validate_equip checks a weapon against it. It covers
weapons only. validate_equip doesn't check a piece of
gear used as a weapon, like a torch, against it. Frozen.
kind
instance-attribute
kind: WeaponPolicyKind
Whether weapon_ids lists the weapons allowed, the weapons refused, or nothing. See
WeaponPolicyKind.
weapon_ids
class-attribute
instance-attribute
The weapon ids the policy lists, like ("long_bow", "two_handed_sword") for the dwarf.
Look each one up with load_equipment().get(item_id), or see
the equipment id index. Empty when kind
is "any", and not empty otherwise.
WeaponPolicyKind
Bases: StrEnum
Whether a class's weapon list contains the weapons it may use or the weapons it may not.
Read it from WeaponPolicy.kind. With "any" the list
is empty and every weapon is allowed. With "allowed" the list contains the only weapons allowed.
With "forbidden" the list contains the only weapons the class may not use. The values are those three strings.
ALLOWED
class-attribute
instance-attribute
Only the listed weapons. The cleric's list contains its blunt weapons.
XpAwardResult
Bases: BaseModel
What an experience award did to a character.
apply_xp returns one. It contains what you need to show a player
the award, how their class changed it, and whether it raised their level. Frozen.
award
instance-attribute
award: int
The award passed to apply_xp, before the class's experience modifier.
modifier_pct
instance-attribute
modifier_pct: int
The class's experience modifier for this character's scores, as a percentage, like 10 or -20. See
xp_modifier_pct.
modified_award
instance-attribute
modified_award: int
The award after the modifier, rounded down. It can be more than the character gained when clamped is True.
xp_after
instance-attribute
xp_after: int
The character's experience points after the award. Character.xp now has this value.
level_after
instance-attribute
level_after: int
The character's level after the award. It's at most one higher than level_before.
clamped
instance-attribute
clamped: bool
True when the award was cut so the character gains no more than one level.
apply_xp cuts an award large enough to reach the level after next to 1
experience point short of that level's threshold, and the rest of the award is lost.
level_up
instance-attribute
level_up: LevelUpResult | None
What the new level gave the character, or None when the award raised no level. See
LevelUpResult.
XpTier
Bases: BaseModel
One tier of a class's experience modifier: a percentage, and the minimum scores that earn it.
A class adjusts every experience award up for a character whose prime requisites are high, and
down for one whose prime requisites are low. Read a class's tiers from
ClassDefinition.xp_tiers.
xp_modifier_pct checks them in order and returns the
percentage of the first tier whose minimums the character meets. Frozen.
modifier_pct
instance-attribute
modifier_pct: int
The adjustment as a percentage, like 10 for a tenth more experience or -20 for a fifth less.
minimums
instance-attribute
minimums: Annotated[Mapping[AbilityScore, int], FrozenMap]
The lowest score in each ability that earns this tier, keyed by ability. The character must meet every entry for the tier to apply. There's at least one entry.
apply_xp
apply_xp(character: Character, definition: ClassDefinition, award: int, stream: RngStream) -> XpAwardResult
Give a character experience points, and raise their level when the new total reaches the next level.
This is how characters advance. B/X divides the experience a party earns evenly among the
surviving members, rounded down. Work out each member's share, then call this once for each
member with that share. It applies the class's experience modifier, adds the result to
the character's xp, and calls level_up when the total
reaches the next level's threshold. In a session,
GameSession.award_adventure_xp,
GameSession.award_immediate_xp, and
the AwardXP command call it for you.
One award never raises a character more than one level. An award large enough to reach the
level after next is cut to 1 point short of that level's threshold, and the rest is lost. A
first-level character who earns enough for third level ends at second level. The result's
clamped is True when an award was cut.
At the class's maximum level, the character gains no more levels, but the whole award still
adds to xp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The character receiving the award. Changed in place: experience points, and on a new level, the level and hit points too. |
required |
definition
|
ClassDefinition
|
The character's class definition. Its |
required |
award
|
int
|
The experience points to award, before the class's modifier. Not negative. |
required |
stream
|
RngStream
|
The stream for the hit die of a new level, usually
|
required |
Returns:
| Type | Description |
|---|---|
XpAwardResult
|
The award, how the class changed it, and what the character gained. Its |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
ADVANCEMENT_STREAM,
CHARACTER_CREATION_STREAM,
create_character,
)
from osrlib.core.classes import apply_xp
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
streams = RngStreams(master_seed=2)
fighter = load_classes().get("fighter")
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=streams.get(CHARACTER_CREATION_STREAM),
).character
result = apply_xp(character, fighter, 10000, streams.get(ADVANCEMENT_STREAM))
print(result.modified_award, result.xp_after, result.level_after, result.clamped)
# 10000 3999 2 True
detection_chance
detection_chance(character: Character, definition: ClassDefinition, kind: str) -> int
Return a character's chance in 6 at one kind of search.
Call it before detection_check, and pass the number
it returns. It reads the class's abilities, and a thief's skill row for listening, so you don't
need to know which classes are better at which search.
"listening": the thief'shear_noisechance for a class with thief skills. Otherwise the class'slistening_at_doorsability, which the dwarf, the elf, and the halfling have at 2. Otherwise 1."secret_doors": the class'sdetect_secret_doorsability, which the elf has at 2. Otherwise 1."room_traps": the class'sdetect_room_trapsability, which the dwarf has at 2. Otherwise- A trap on a chest is a thief skill instead,
find_remove_treasure_traps. "construction", noticing unusual stonework like a sloping passage or a sliding wall: the class'sdetect_construction_tricksability, which the dwarf has at 2. Otherwise 0, because the SRD gives this chance only to dwarves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The character searching. For a thief, the function reads the skill row for their level. |
required |
definition
|
ClassDefinition
|
The character's class. Its |
required |
kind
|
str
|
What the character is searching for: |
required |
Returns:
| Type | Description |
|---|---|
int
|
The chance in 6. A chance of 0 means the character can't succeed, and
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.classes import detection_chance
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
dwarf = load_classes().get("dwarf")
character = create_character(
name="Thora",
class_id="dwarf",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=RngStreams(master_seed=1).get(CHARACTER_CREATION_STREAM),
).character
print(detection_chance(character, dwarf, "room_traps"))
# 2
print(detection_chance(character, dwarf, "secret_doors"))
# 1
detection_check
detection_check(chance_in_six: int, *, stream: RngStream) -> DetectionResult
Roll 1d6 against a chance in 6, and succeed on a roll equal to or under the chance.
This one roll covers searching for a secret door, listening at a door, spotting a trap in a
room, and a dwarf noticing unusual stonework. It also covers forcing a stuck door open, with
Character.open_doors_chance as the
chance. For a search, get the character's chance from
detection_chance and pass it here. In a session,
the engine makes the roll for you when it resolves commands like
Search and
ListenAtDoor.
A chance of 0 or less fails without throwing a die, and the stream doesn't advance. No die is thrown for a character who can't succeed, like anyone but a dwarf looking for unusual stonework.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chance_in_six
|
int
|
The chance to roll equal to or under, usually from
|
required |
stream
|
RngStream
|
The stream to draw from, usually the one a session uses for these checks,
|
required |
Returns:
| Type | Description |
|---|---|
DetectionResult
|
The roll and whether it succeeded. |
Examples:
from osrlib.core.classes import detection_check
from osrlib.core.rng import RngStreams, StreamName
stream = RngStreams(master_seed=4).get(StreamName.EXPLORATION)
result = detection_check(2, stream=stream)
print(result.roll, result.passed)
# 2 True
nothing = detection_check(0, stream=stream)
print(nothing.roll, nothing.passed)
# None False
drain_levels
drain_levels(
character: Character,
definition: ClassDefinition,
*,
levels: int = 1,
xp_policy: str,
stream: RngStream,
spawn_consequence: str | None = None,
spell_catalog: SpellCatalog | None = None
) -> DrainResult
Take experience levels away from a character, reversing what level_up does.
Energy drain is the attack of some undead: a wight's touch takes one level, and a spectre's or
a vampire's takes two. You rarely call this yourself, because
resolve_energy_drain reads the monster's
energy_drain ability and calls it for you. Call it directly for a drain that doesn't come
from a monster, like a cursed scroll.
Each level is lost the way level_up gains it, read from the
hit dice of the level being lost and the level below it. When the level being lost has more
hit dice, the character rolls that die and loses the result plus the CON modifier, at least 1.
The CON modifier counts only when the lost level's con_applies is True. When the two levels
have the same number of dice, no die is rolled, and the loss is the difference between their
flat bonus values. A character has no record of the dice behind their hit points, so this
function rolls a new die for each lost level. THAC0, saving throws, and spell slots come from
the level, so they need no update.
While a character has a level left, neither maximum nor current hit points drops below 1. Losing
the last level kills the character, as the SRD rules for a character drained of all levels.
The result's slain is then True, its new_level is 0, and its events include the death. The
character's level stays at 1, because the model doesn't allow a level below 1, and their
experience becomes 0. A character who survives forgets memorized spells that no longer fit the
lower level's spell slots, the most recently memorized first. The function looks up the level of
each memorized spell in spell_catalog.
Experience points change once, after every level is taken. Under "halfway", the character is
left with the point halfway between the threshold of the level they had and the threshold of
their new level. Under "level_minimum", they're left with exactly the new level's threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The character being drained. Changed in place: level, experience points, and both hit point totals. |
required |
definition
|
ClassDefinition
|
The character's class definition. Its |
required |
levels
|
int
|
How many levels to take, 1 or more. |
1
|
xp_policy
|
str
|
|
required |
stream
|
RngStream
|
The stream for the hit dice, usually
|
required |
spawn_consequence
|
str | None
|
A description of what a victim drained of all levels becomes, like the
description of the monster's |
None
|
spell_catalog
|
SpellCatalog | None
|
The spells the character's memorized copies come from, or |
None
|
Returns:
| Type | Description |
|---|---|
DrainResult
|
What the character lost, and the events that describe it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
ADVANCEMENT_STREAM,
CHARACTER_CREATION_STREAM,
create_character,
)
from osrlib.core.classes import apply_xp, drain_levels
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
streams = RngStreams(master_seed=2)
fighter = load_classes().get("fighter")
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=streams.get(CHARACTER_CREATION_STREAM),
).character
advancement = streams.get(ADVANCEMENT_STREAM)
apply_xp(character, fighter, 2500, advancement)
print(character.level, character.xp, character.max_hp)
# 2 2500 10
result = drain_levels(character, fighter, levels=1, xp_policy="halfway", stream=advancement)
print(result.levels_lost, result.new_level, result.hp_lost, result.slain)
# 1 1 9 False
# The lost level's d8 came up 8, and Rurik's CON modifier adds 1, so the drain takes 9
# hit points: maximum hit points fall from 10 to 1.
print(character.level, character.xp, character.max_hp)
# 1 1000 1
level_title
level_title(definition: ClassDefinition, level: int) -> str | None
Return the title of a character of this class and level, like "Veteran" for a first-level fighter.
Use it wherever you show a character's rank, like a character sheet, a party list, or the message you show when a character gains a level.
The SRD prints titles only up to name level, the level at which a character may build a
stronghold. Past the last title, this returns None, so show the class name instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The character's class. |
required |
level
|
int
|
The level to name, from 1 to the class's |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The title, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
level_up
level_up(character: Character, definition: ClassDefinition, stream: RngStream) -> LevelUpResult
Raise a character one level and roll the hit points that come with it.
In ordinary play, call apply_xp instead. It awards
experience and calls this when the total reaches the next level. Call this yourself when a
character gains a level without earning the experience, like a character you create above
first level or a level the referee grants.
The hit point gain depends on the hit dice of the new level. When the new level has more hit dice
than the level below it, the character rolls one die, adds the CON modifier, and gains at
least 1 hit point. When it has the same number, no die is rolled, and the character gains the
difference between the two levels' flat bonus values. The CON modifier counts only when the
new level's con_applies is True. The result's
con_applied is True when it counted.
For the built-in classes, both change at the first level past name level, the level at which a
character may build a stronghold. Up to name level, a character rolls a die and adds CON.
After it, the character gains a flat amount without CON. A class you write yourself can set
count and con_applies separately, so read con_applied rather than working it out from the
level.
Maximum and current hit points both rise by the gain, so a wounded character stays wounded by the same amount. THAC0, saving throws, and spell slots come from the new level's progression row, so they need no update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The character to advance. Changed in place: its level, maximum hit points, and current hit points. |
required |
definition
|
ClassDefinition
|
The character's class definition. Its |
required |
stream
|
RngStream
|
The stream for the hit die, usually
|
required |
Returns:
| Type | Description |
|---|---|
LevelUpResult
|
What the new level gave the character, including the die result when a die was rolled. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
ADVANCEMENT_STREAM,
CHARACTER_CREATION_STREAM,
create_character,
)
from osrlib.core.classes import level_up
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
streams = RngStreams(master_seed=2)
fighter = load_classes().get("fighter")
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=streams.get(CHARACTER_CREATION_STREAM),
).character
result = level_up(character, fighter, streams.get(ADVANCEMENT_STREAM))
print(result.new_level, result.hp_roll, result.hp_gained)
# 2 1 2
print(character.level, character.max_hp, character.thac0)
# 2 10 19
thief_skill_check
thief_skill_check(
character: Character, definition: ClassDefinition, skill: str, *, modifier_pct: int = 0, stream: RngStream
) -> SkillCheckResult
Roll one of a thief's skills and return the result.
Call it when a thief tries something a thief skill covers, like climbing a wall, listening at a
door, or picking a pocket. It rolls and returns the result, and does nothing else. It emits no
events, and it doesn't decide what the players may see. If you show players only what their
characters know, you decide what to reveal. In a session, the engine calls it and emits the
events for you when it resolves commands like PickLock.
For a skill in PERCENTILE_THIEF_SKILLS, it
rolls d%, and the check succeeds on a roll equal to or under the chance for the thief's level.
For "hear_noise", it rolls 1d6 against a chance in 6 instead, and ignores modifier_pct.
Picking pockets has two more rules. Stealing from a victim above fifth level is harder by 5%
for each level above the fifth. This function takes no victim, so include that penalty in
modifier_pct yourself. The function then lowers the chance to 99 if it's higher, so a theft
can always fail. A roll of more than twice the chance means the victim noticed the attempt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The thief making the attempt. The check uses the skill row for their level. |
required |
definition
|
ClassDefinition
|
The character's class. Its |
required |
skill
|
str
|
One of the names in
|
required |
modifier_pct
|
int
|
A percentage added to the chance before rolling. Make it negative to make
the attempt harder. Ignored for |
0
|
stream
|
RngStream
|
The stream to draw from, usually the one a session uses for these checks,
|
required |
Returns:
| Type | Description |
|---|---|
SkillCheckResult
|
The roll, the chance it was checked against, and whether it succeeded. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.classes import thief_skill_check
from osrlib.core.rng import RngStreams, StreamName
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
thief = load_classes().get("thief")
character = create_character(
name="Nim",
class_id="thief",
alignment=Alignment.NEUTRAL,
ruleset=Ruleset(),
stream=RngStreams(master_seed=4).get(CHARACTER_CREATION_STREAM),
).character
stream = RngStreams(master_seed=1).get(StreamName.EXPLORATION)
result = thief_skill_check(character, thief, "climb_sheer_surfaces", stream=stream)
print(result.roll, result.chance, result.passed)
# 65 87 True
stream = RngStreams(master_seed=9).get(StreamName.EXPLORATION)
theft = thief_skill_check(character, thief, "pick_pockets", stream=stream)
print(theft.roll, theft.chance, theft.passed, theft.noticed)
# 100 20 False True
xp_modifier_pct
xp_modifier_pct(definition: ClassDefinition, scores: dict[AbilityScore, int]) -> int
Return how much a class adjusts a character's experience awards, as a percentage.
A class raises every experience award for a character with high prime requisites and lowers it
for one with low prime requisites. apply_xp calls this for
you. Call it yourself to show the modifier on a character sheet, or to show a player what a
trade of ability points at creation would change.
This function checks the class's xp_tiers in order, highest percentage first, and the first
tier whose minimums the scores meet applies. Scores that meet no tier get no adjustment. That's
how the elf and the halfling have bonus tiers and no penalty tiers, as the SRD prints them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The character's class. |
required |
scores
|
dict[AbilityScore, int]
|
The character's final ability scores, after any adjustment at creation. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The adjustment as a percentage: |
Examples:
from osrlib.core.abilities import AbilityScore
from osrlib.core.classes import xp_modifier_pct
from osrlib.data import load_classes
fighter = load_classes().get("fighter")
scores = dict.fromkeys(AbilityScore, 12)
scores[AbilityScore.STR] = 16
print(xp_modifier_pct(fighter, scores))
# 10
scores[AbilityScore.STR] = 5
print(xp_modifier_pct(fighter, scores))
# -20