osrlib.core.character
Player characters: the model, the functions that create one, and the documents that store one.
Start here when you need a party. create_character is
the entry point. Pass it a name, a class id, an alignment, a Ruleset,
and a seeded random-number stream from osrlib.core.rng. It returns a
first-level Character and the raw dice it rolled. Put the
characters you create into a Party to play them, or pass them to the
combat, magic, and item functions in osrlib.core on their own.
Character is a mutable pydantic model. Its derived values are
properties computed from the stored fields each time you read them. They include THAC0 (the d20
roll needed to hit armour class 0), the saving throws, the ability modifiers, both armour classes,
and the language list. Validation on the model is
structural: the scores are in range, the level is within the class's maximum, and current hit
points are no higher than maximum. The model can't check whether a character was created legally,
because a finished character has no record of the choices that made it. The creation functions
check each choice when it's made.
To create a character one step at a time while a player makes the choices, call these functions in the order the SRD gives for creating a character:
roll_ability_scoresrolls the six ability scores.validate_class_choicechecks the scores against the class the player picks.validate_adjustmentandapply_adjustmentcheck and apply a trade of ability points, if the player wants one.validate_starting_spellschecks an arcane caster's first spell.roll_hit_pointsrolls first-level hit points.validate_extra_languageschecks the extra languages a high INT allows.roll_starting_goldrolls the starting money.
Then construct the Character from the results. Pass the
scores as scores, the hit points as both max_hp and current_hp, level=1, xp=0, the class
definition's race, and the name, class id, alignment, and extra languages. For a class you
wrote, pass its definition as custom_class too. To use scores a player
chose instead of rolled ones, skip step 1 and pass those scores. Write the spell
book with choose_starting_spells, and buy and
equip gear with validate_purchase,
purchase, and equip. Each validating
function returns a list of Rejection records rather than
raising, so you can show the player what went wrong and let them choose again.
create_character runs the same steps in one call when
every choice is known in advance, and raises ValueError on the first illegal choice instead. No
creation function emits events, because creation happens before a session starts.
Advancement is in osrlib.core.classes: experience awards, leveling up, and
energy drain, which takes levels away. To store a character on its own, call
to_document. To store a group of characters, call
party_to_document. To store a whole game in progress,
characters included, call save_game.
Creation and advancement draw from two separate streams, keyed by
CHARACTER_CREATION_STREAM and
ADVANCEMENT_STREAM. A stream key is the name of one
independent random-number sequence in an RngStreams set. The two
streams are separate so that a change to the creation rules never changes the level-up rolls in a
save you've already made.
Typical usage:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.party import Party
streams = RngStreams(master_seed=2)
stream = streams.get(CHARACTER_CREATION_STREAM)
result = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
purchases=[("sword", 1), ("leather", 1)],
equip_ids=["sword", "leather"],
)
party = Party(members=[result.character])
print(party.members[0].name, party.members[0].max_hp, party.members[0].armour_class)
# Rurik 8 6
ABILITY_ROLL_ORDER
module-attribute
ABILITY_ROLL_ORDER: Final = (
AbilityScore.STR,
AbilityScore.INT,
AbilityScore.WIS,
AbilityScore.DEX,
AbilityScore.CON,
AbilityScore.CHA,
)
The order in which roll_ability_scores rolls the six abilities.
The order is STR, INT, WIS, DEX, CON, CHA, as the SRD lists them. Read it to show rolled scores in the order the dice came up, or to match recorded rolls to their abilities by hand. The order never changes, so the same stream always gives the same six scores.
ADVANCEMENT_STREAM
module-attribute
ADVANCEMENT_STREAM = StreamName.ADVANCEMENT
The stream key for advancement draws, "advancement": the hit dice rolled when a level is gained or lost.
Pass streams.get(ADVANCEMENT_STREAM) as the stream argument of
apply_xp, level_up, and
drain_levels. A
GameSession uses this key when it awards experience and when
it resolves energy drain.
It is separate from
CHARACTER_CREATION_STREAM. A change to the
creation rules can change how many draws creation takes. Because the streams are separate, that
change doesn't change the advancement rolls in a save you've already made.
CHARACTER_CREATION_STREAM
module-attribute
CHARACTER_CREATION_STREAM = StreamName.CHARACTER_CREATION
The stream key for character-creation draws, "character_creation".
A stream key is the name of one independent random-number sequence in an
RngStreams set. Pass streams.get(CHARACTER_CREATION_STREAM) as the
stream argument of create_character and of the
stepwise creation functions. create_character draws the ability scores, the first-level hit
points, and the starting gold from it, in that order.
To roll a whole party from one seed, pass the same stream to each call. Each character's draws continue where the previous character's stopped, so the same seed and the same calls always give the same party.
AbilityScoreRolls
Bases: BaseModel
The six rolled ability scores, with the dice behind each, so you can show them.
roll_ability_scores returns one, and
create_character includes one in its result. Pass
scores to validate_class_choice. Frozen.
scores
instance-attribute
scores: dict[AbilityScore, int]
The total of each ability's three dice, keyed by AbilityScore. All six
abilities are present, each from 3 to 18.
Character
Bases: BaseModel
A player character: the stored state of one character, and the values derived from it.
Get one from create_character, or from
from_document when you load a stored
character. Construct one directly when you create a character step by step with the other
creation functions in this module, or when you already have every value, as in a test.
Put characters in a Party to explore with them. Pass one to the
functions in osrlib.core.combat as an attacker or a target, to the
functions in osrlib.core.spells as a caster, and to
apply_xp or level_up to
advance it. A MonsterInstance has the same combat
attributes, so the combat functions take either.
The model is mutable and validates on assignment. Setting a field to a value that breaks a rule
raises a pydantic ValidationError, and every field still has the value it had before the
assignment. Validation is structural only. It checks that the six scores
are present and in range, that class_id is the id of a class in
load_classes or of the definition in
custom_class, that the level is within the
class's maximum, and that current hit points don't exceed maximum hit points. It doesn't check
that the character was created legally, because a finished character has no record of how it was
created.
Nothing derived is stored. THAC0, attack bonus, saving throws, ability modifiers, both armour classes, and the language list are properties recomputed from the stored fields each time you read them, so a level change or a swapped piece of armour shows up at once.
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
).character
print(character.level, character.thac0, character.saves.death)
# 1 19 12
character.current_hp -= 3
print(character.current_hp, character.max_hp)
# 5 8
id
class-attribute
instance-attribute
id: str | None = None
The character's id within a game, like "character-0001", or None before a session assigns one.
GameSession.new assigns an id from the session's
IdAllocator to each party member whose id is None.
AddMember does the same for a character who joins during play. Commands refer
to a character by this id. An event about a character with no id uses the character's name instead.
name
class-attribute
instance-attribute
The character's name, for display. It can't be empty.
class_id
instance-attribute
class_id: str
The id of the character's class, like "fighter".
For a class osrlib includes, the id comes from load_classes and is listed in
the class id index. For a class you wrote,
it's the id of the definition in custom_class. Read
definition for the class itself.
custom_class
class-attribute
instance-attribute
custom_class: ClassDefinition | None = None
The definition of the character's class when it's a class you wrote, or None for a class osrlib includes.
Set it to your ClassDefinition, and set class_id to the definition's
id. definition returns it, so the kernel functions and a
GameSession play the character under your class.
create_character sets it when you pass custom_class.
The model refuses a definition whose id isn't class_id. It also refuses a definition whose id is the id of a
built-in class, because a class id refers to one class. Give a variant of a built-in class a different id.
The definition is part of the character, so to_document,
party_to_document, and save_game
include it, and loading the document gives it back. Your game doesn't supply the class again to load one.
race
class-attribute
instance-attribute
level
class-attribute
instance-attribute
The experience level, 1 through the class's maximum.
xp
class-attribute
instance-attribute
The character's total experience points.
Award experience with apply_xp, which adds to this total and levels the character
up when it reaches the next level's threshold. Assigning a new total here doesn't change the level.
scores
instance-attribute
scores: dict[AbilityScore, int]
The six ability scores, each 3 through 18, keyed by AbilityScore. All six
must be present.
They're the scores the character rolled, after any adjustment at creation. A STR that an item sets, like the 18 of
gauntlets of ogre power, doesn't change them. Read
effective_strength for the STR the rules use during play.
alignment
instance-attribute
alignment: Alignment
Lawful, neutral, or chaotic. It sets the secret language in
alignment_tongue.
extra_languages
class-attribute
instance-attribute
The language ids chosen at creation because of a high INT. Check the choice with
validate_extra_languages before you store it.
current_hp
class-attribute
instance-attribute
Current hit points, from 0 up to max_hp.
A character at 0 hit points is out of the fight. Whether a character is dead is the dead condition, which
kill applies, not a hit point value.
nonregen_damage
class-attribute
instance-attribute
The fire and acid damage that a worn ring of regeneration can't heal, up to max_hp.
While the character wears the ring, deal_damage adds fire and acid damage
here. The ring heals the character only up to max_hp less this amount. Other healing, like a potion, heals this
damage too. So each time the character takes damage while wearing the ring, deal_damage first lowers this value
to the damage the character had before that hit. It's 0 for a character who has never worn the ring.
inventory
class-attribute
instance-attribute
Everything the character carries, wears, and wields, and their coins. See
Inventory and the buying and equipping functions in
osrlib.core.items.
carrying_treasure
class-attribute
instance-attribute
carrying_treasure: bool = False
Whether the character is carrying enough treasure to slow them down, under basic encumbrance.
The basic encumbrance rules leave the amount to the referee, so osrlib leaves it to you. Set this flag, and
movement_rate drops the character to the next slower rate.
The other encumbrance modes ignore it.
conditions
class-attribute
instance-attribute
conditions: tuple[ActiveCondition, ...] = ()
The conditions in effect, like poisoned or paralysed.
Apply and clear them with the functions in osrlib.core.effects. Test for one with
has_condition.
stat_modifiers
class-attribute
instance-attribute
stat_modifiers: tuple[ActiveModifier, ...] = ()
Timed bonuses and penalties from spells and items. The functions in
osrlib.core.effects apply and remove them.
spell_book
class-attribute
instance-attribute
The spell ids in an arcane caster's spell book, in the order they were added.
An arcane caster memorizes spells only from this book. It's empty for divine casters like the cleric, who memorize from their whole class list, and for classes that cast no spells.
memorized_spells
class-attribute
instance-attribute
memorized_spells: tuple[MemorizedSpell, ...] = ()
The spells the caster has memorized and can cast, as MemorizedSpell
records in the order they were memorized.
Fill it with memorize_spells. Casting spends the first matching copy in
the list, and energy drain removes copies from the end. How many spells of each level fit comes from the class's
progression row for the current level, so it changes when the level does.
definition
property
definition: ClassDefinition
The character's class: custom_class when it's set.
When custom_class is None, it's the built-in class whose id is class_id, from
load_classes.
Read it for anything that depends on the class: the progression table, the armour and weapon
policies, the class abilities, and the level titles. Pass it as the definition argument of the
functions in osrlib.core.classes. A
GameSession reads it for each member too.
load_classes loads the catalog once and caches it, so
reading this property again costs almost nothing.
thac0
property
thac0: int
The d20 roll the character needs to hit armour class 0, from the current level's progression row.
THAC0 goes with descending armour class, where a lower armour class is better. If you show
ascending armour class instead, use
attack_bonus. The two describe the same
attack.
attack_bonus
property
attack_bonus: int
The bonus added to an attack roll under ascending armour class, from the current level's progression row.
It's thac0 for ascending armour class, where a
higher armour class is better. Both come from the same row, so they always agree.
saves
property
saves: SavingThrows
The five saving throw targets for the current level, from the progression row.
A save succeeds on a d20 roll equal to or higher than the target for the kind of danger.
saving_throw rolls one for you. The targets change as
soon as the level does.
effective_strength
property
effective_strength: int
The STR score the rules use during play.
It's the rolled STR in scores, unless something sets the
character's STR to a fixed score:
- A character who wears gauntlets of ogre power has STR 18.
- A character under the curse of a ring of weakness has STR 3. The curse takes hold six rounds after the character puts the ring on. When the character also wears the gauntlets, the curse's 3 applies.
These come from strength_set modifiers. If you write content of your own with one, the engine looks for a
set score first on the effects attached to the character, in the order they were attached, and then on the
equipped magic items, in equipped order.
melee_modifier,
open_doors_chance, and the wielder's will in
sword_control_check come from this score. The rules for creating
and advancing a character read the rolled score instead: a class's minimum scores, the trade of ability points
at creation, and the experience modifier for a prime requisite. A set score never changes scores, so to
show a player what an item did, show both numbers. The player view has both, as
MemberView.effective_strength and
MemberView.scores.
Examples:
from osrlib.core.abilities import AbilityScore
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.items import MagicItemInstance, equip
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
rurik = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
).character
gauntlets = MagicItemInstance(instance_id="magic-item-0001", template_id="gauntlets_of_ogre_power")
rurik.inventory.items.append(gauntlets)
equip(rurik.inventory, rurik.definition, gauntlets)
print(rurik.scores[AbilityScore.STR], rurik.effective_strength, rurik.melee_modifier)
# 10 18 3
melee_modifier
property
melee_modifier: int
The STR modifier added to melee attack rolls and to melee damage, unarmed attacks included, from −3 to +3.
It comes from effective_strength. So a character who
wears gauntlets of ogre power has the modifier for STR 18, which is +3, and a character under the curse of a
ring of weakness has the modifier for STR 3, which is −3. The combat functions add this modifier for you.
open_doors_chance
property
open_doors_chance: int
The chance in 6 of forcing a stuck door open, from STR.
It comes from effective_strength. So it's 5 for a
character who wears gauntlets of ogre power, and 1 for a character under the curse of a ring of weakness.
Roll 1d6, and the door opens on a roll equal to or less than this number. To roll it, pass
it to detection_check. In a session, the engine
reads it for you when it resolves a ForceDoor
command.
missile_modifier
property
missile_modifier: int
The DEX modifier added to missile attack rolls, from −3 to +3. It doesn't change damage.
initiative_modifier
property
initiative_modifier: int
The DEX modifier to an individual initiative roll, from −2 to +2.
It applies only when the individual_initiative flag of the
Ruleset is on. With group initiative, the default, each
side rolls once, and this modifier doesn't apply.
hit_point_modifier
property
hit_point_modifier: int
The CON modifier added to each hit die rolled, from −3 to +3.
roll_hit_points and
level_up add it to each die, and a die always gains at
least 1 hit point, however low the CON.
magic_save_modifier
property
magic_save_modifier: int
The WIS modifier applied to saving throws against magical effects, from −3 to +3.
npc_reaction_modifier
property
npc_reaction_modifier: int
The CHA modifier to a monster reaction roll when this character talks to the monsters, from −2 to +2.
Pass it as the modifier of roll_reaction. In a
session, the engine applies the speaker's modifier for you when it resolves a
Parley command.
alignment_tongue
property
alignment_tongue: str
The secret language everyone of this alignment speaks, as a language id.
Every character speaks the tongue of their alignment and no other. The id is
alignment_ followed by the alignment's value, so a lawful character speaks
"alignment_lawful". These ids aren't in the language catalog that
load_languages returns. This property builds the id from
alignment, so a change of alignment changes the tongue at once.
languages
property
Every language the character speaks, as language ids.
The alignment tongue comes first. The languages the class grants come next, starting with
"common". The extra languages chosen at creation come last. To find out whether two
characters can talk to each other, look for an id in both lists. Every id except the
alignment tongue is a catalog id from load_languages, listed
in the language id index.
armour_class
property
armour_class: int
The character's descending armour class, where lower is better.
An unarmoured character is 9. Worn armour sets the base. A shield's bonus, the bonus of a
worn ring that protects all the time, and the DEX modifier each subtract from it. It's
computed from the inventory each time you read it, so equipping or removing armour changes
it at once. If you show ascending armour class, use
armour_class_ascending.
armour_class_ascending
property
armour_class_ascending: int
The character's ascending armour class, where higher is better.
An unarmoured character is 10, and every bonus adds to it. It describes the same defense
as armour_class, so the two always
agree.
movement_rate
Return how far this character moves in one exploration turn, in feet.
What sets the rate depends on the encumbrance mode of the ruleset. Under none, every
character moves 120 feet. Under basic, the rate depends on the worn armour and on the
carrying_treasure flag. Under
detailed, it depends on the total weight carried. Under basic and detailed, a
character carrying more than the maximum load can't move, and the rate is 0.
A party moves at the rate of its slowest living member. For a party, call
Party.movement_rate instead of calling this for
each member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ruleset
|
Ruleset
|
The ruleset in play. What counts depends on its |
required |
Returns:
| Type | Description |
|---|---|
int
|
The rate in feet per turn: 120, 90, 60, 30, or 0. |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
ruleset = Ruleset()
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=ruleset,
stream=stream,
purchases=[("plate_mail", 1)],
equip_ids=["plate_mail"],
).character
print(character.movement_rate(ruleset))
# 60
to_document
Return this character as a JSON-ready document stamped with its schema and engine versions.
Use it to store one character on its own, like a character a player keeps between games.
To store a group of characters, use
party_to_document. To store a game in
progress, use save_game, which includes the characters.
Load the document with from_document.
The version stamp lets a later release of osrlib tell whether it can read the document.
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
A dict with the keys |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, Character, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
character = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
).character
document = character.to_document()
print(sorted(document))
# ['engine_version', 'kind', 'payload', 'schema_version']
print(Character.from_document(document).name)
# Rurik
from_document
classmethod
Rebuild a character from a document written by to_document.
This method ignores fields in the payload that this release doesn't recognize, so a document from a later release that only added fields still loads. It refuses a document with a newer schema version than this release supports, because the fields this release reads may mean something different in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Mapping[str, object]
|
The document |
required |
Returns:
| Type | Description |
|---|---|
Character
|
A new character, with every derived value computed from the loaded fields. |
Raises:
| Type | Description |
|---|---|
ContentValidationError
|
If the document isn't a character document, or its payload
doesn't validate as a character. The document is damaged or isn't one
|
SaveVersionError
|
If the document's schema version is newer than this release supports. Upgrade osrlib to load it. |
Examples:
Store a character as JSON and load it back:
import json
from pathlib import Path
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, Character, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
rurik = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
purchases=[("sword", 1)],
).character
Path("rurik.json").write_text(json.dumps(rurik.to_document()))
loaded = Character.from_document(json.loads(Path("rurik.json").read_text()))
print(loaded.name, loaded.max_hp, loaded.thac0, [item.template.id for item in loaded.inventory.items])
# Rurik 8 19 ['sword']
CharacterCreationResult
Bases: BaseModel
What create_character returns: the character, and the dice behind it.
Use character, and show the rolls if you want a player to see how the character came out.
Frozen.
character
instance-attribute
character: Character
The new Character, at first level, with its purchases in its inventory and
its equipment worn or wielded.
ability_rolls
instance-attribute
ability_rolls: AbilityScoreRolls
The ability scores as rolled, before any adjustment. Compare them with character.scores to show what the
adjustment changed.
hit_point_roll
instance-attribute
hit_point_roll: HitPointRoll
The first-level hit point roll, with every die thrown.
gold_roll
instance-attribute
gold_roll: RollResult
The 3d6 × 10 roll for starting money. Its total is the gold pieces the character had before paying for the
purchases.
HitPointRoll
Bases: BaseModel
A first-level hit point roll: every die thrown, and the hit points the character starts with.
roll_hit_points returns one, and
create_character includes one in its result. Use
hit_points as the new character's max_hp and current_hp. Frozen.
rolls
instance-attribute
Every die result, before the CON modifier, in the order thrown.
With the hp_reroll_at_first_level option of Ruleset on, the 1s and 2s that were
thrown again are here too, and the last entry is the die that counts. Otherwise there's one entry.
choose_starting_spells
choose_starting_spells(
character: Character, definition: ClassDefinition, catalog: SpellCatalog, spell_ids: Sequence[str]
) -> list[Rejection]
Write an arcane caster's starting spell book onto the character.
Use it when you create a character step by step and the player has chosen their first spell.
It refuses a character whose book already has spells in it, checks the choice with
validate_starting_spells, and then stores
the ids in spell_book. When it refuses
anything, it writes nothing. create_character
writes the book for you when you pass starting_spell_ids.
A spell in the book can't be cast yet. To prepare spells for casting, call
memorize_spells. An arcane caster memorizes spells
only from the book.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
character
|
Character
|
The character to write to. Changed in place when the choice is legal. |
required |
definition
|
ClassDefinition
|
The character's class. Its |
required |
catalog
|
SpellCatalog
|
The spell catalog from |
required |
spell_ids
|
Sequence[str]
|
The chosen spell ids, from |
required |
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
One |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
CHARACTER_CREATION_STREAM,
choose_starting_spells,
create_character,
)
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes, load_spells
magic_user = load_classes().get("magic_user")
stream = RngStreams(master_seed=3).get(CHARACTER_CREATION_STREAM)
character = create_character(
name="Miri",
class_id="magic_user",
alignment=Alignment.NEUTRAL,
ruleset=Ruleset(),
stream=stream,
starting_spell_ids=["sleep"],
).character
rejections = choose_starting_spells(character, magic_user, load_spells(), ["magic_missile"])
print([rejection.code for rejection in rejections])
# ['magic.book.already_chosen']
print(character.spell_book)
# ('sleep',)
create_character
create_character(
*,
name: str,
class_id: str,
alignment: Alignment,
ruleset: Ruleset,
stream: RngStream,
custom_class: ClassDefinition | None = None,
adjustment: AbilityAdjustment | None = None,
starting_spell_ids: Sequence[str] = (),
spell_catalog: SpellCatalog | None = None,
extra_languages: Sequence[str] = (),
purchases: Sequence[tuple[str, int]] = (),
equip_ids: Sequence[str] = ()
) -> CharacterCreationResult
Create a first-level character in one call, with every choice passed in.
Start here to make characters. Pass a name, a class id, an alignment, a ruleset, and a seeded
stream, and it rolls the whole character: ability scores, hit points, and starting gold. It
also makes the choices you pass: a trade of ability points, the first spell, extra languages,
and the gear to buy and equip. Put the characters you create into a
Party, and pass the party to
GameSession.new to start a game.
To get a stream, make an RngStreams set from a seed and ask it
for the creation stream: RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM). The same
seed and the same arguments always create the same character. To roll a whole party from one
seed, pass the same stream to each call, and each call continues where the last one stopped.
You make every choice before the call, which suits a script or a ready-made character. When a
player chooses as they go, call the step-by-step functions in this module instead. Those return
Rejection records you can show the player. This function
raises ValueError on the first illegal choice and reports nothing more.
Before the first roll, it checks every choice that doesn't depend on a rolled score: the name, the class, the spell book, the rules of the ability trade that read no score, the extra languages, and the purchases and the items to equip, all but their price. When one of these choices is illegal, the call raises and the stream stays where it was.
Then the steps run in the SRD's order: roll the six scores, check them against the class's requirements, apply the ability adjustment, roll hit points, check how many extra languages the INT allows, roll starting gold, then buy and equip. The stream advances in that order, so the scores are always rolled first and the gold last. The checks take no draws. The checks in these steps need a rolled score or the rolled gold, so they raise after the stream has advanced: scores that miss the class's requirements, a trade that would take a score below 9 or above 18, more languages than the INT allows, and purchases the gold can't cover. Call again with the same stream to roll new scores, or choose another class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The character's name. |
required |
class_id
|
str
|
The class to play, like |
required |
alignment
|
Alignment
|
Lawful, neutral, or chaotic. |
required |
ruleset
|
Ruleset
|
The ruleset in play. When its |
required |
stream
|
RngStream
|
The stream for the creation draws, usually
|
required |
custom_class
|
ClassDefinition | None
|
The definition of a class you wrote, or |
None
|
adjustment
|
AbilityAdjustment | None
|
A trade of ability points, as an
|
None
|
starting_spell_ids
|
Sequence[str]
|
The spells in an arcane caster's starting spell book, by their ids in
|
()
|
spell_catalog
|
SpellCatalog | None
|
The spells a new caster can start with, or |
None
|
extra_languages
|
Sequence[str]
|
The extra languages a high INT allows, from
|
()
|
purchases
|
Sequence[tuple[str, int]]
|
What to buy with the starting gold, as |
()
|
equip_ids
|
Sequence[str]
|
The ids of bought items to wear or wield, equipped in the order given. Each one
must be in |
()
|
Returns:
| Type | Description |
|---|---|
CharacterCreationResult
|
The new character, and the dice rolled to create it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On the first illegal choice. Illegal choices are an empty name, an unknown
class, spell, language, or item id, a |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.crawl.party import Party
streams = RngStreams(master_seed=2)
stream = streams.get(CHARACTER_CREATION_STREAM)
result = create_character(
name="Rurik",
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
purchases=[("sword", 1), ("leather", 1)],
equip_ids=["sword", "leather"],
)
character = result.character
print(character.name, character.level, character.max_hp, character.armour_class)
# Rurik 1 8 6
print(character.inventory.worn_armour.template.id, character.inventory.purse.gp)
# leather 30
print(result.gold_roll.total, result.hit_point_roll.rolls)
# 60 (7,)
party = Party(members=[character])
print(party.movement_rate(Ruleset()))
# 90
party_from_document
Rebuild the characters in a document written by party_to_document.
This function validates each character as it loads. If one fails, the whole load fails, so you never get
part of the group. Pass the list to Party as its members to
play them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Mapping[str, object]
|
The document |
required |
Returns:
| Type | Description |
|---|---|
list[Character]
|
New characters, in the order they were stored. |
Raises:
| Type | Description |
|---|---|
ContentValidationError
|
If the document isn't a party document, its payload has no
|
SaveVersionError
|
If the document's schema version is newer than this release supports. Upgrade osrlib to load it. |
Examples:
Save a roster to a JSON file and load it back:
import json
from pathlib import Path
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
CHARACTER_CREATION_STREAM,
create_character,
party_from_document,
party_to_document,
)
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
roster = [
create_character(
name=name,
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
).character
for name in ("Rurik", "Alia")
]
Path("roster.json").write_text(json.dumps(party_to_document(roster)))
characters = party_from_document(json.loads(Path("roster.json").read_text()))
print([(member.name, member.max_hp) for member in characters])
# [('Rurik', 8), ('Alia', 1)]
party_to_document
Return a group of characters as one JSON-ready document, stamped with its schema and engine versions.
Use it to store a group of characters you create once and use again, like a set of ready-made
characters a player can pick from. replay_game also
takes one, as the party the game started with. For that, call this before you pass the
characters to GameSession.new, which assigns their
ids.
The document contains only the characters. Marching order and the rest of a
Party's state belong to a game in progress, which
save_game stores. Load the document with
party_from_document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
characters
|
Sequence[Character]
|
The characters to store, in the order you want them back. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
A dict with the keys |
Examples:
from osrlib.core.alignment import Alignment
from osrlib.core.character import (
CHARACTER_CREATION_STREAM,
create_character,
party_from_document,
party_to_document,
)
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
stream = RngStreams(master_seed=2).get(CHARACTER_CREATION_STREAM)
roster = [
create_character(
name=name,
class_id="fighter",
alignment=Alignment.LAWFUL,
ruleset=Ruleset(),
stream=stream,
).character
for name in ("Rurik", "Alia")
]
document = party_to_document(roster)
print([member.name for member in party_from_document(document)])
# ['Rurik', 'Alia']
roll_ability_scores
roll_ability_scores(stream: RngStream) -> AbilityScoreRolls
Roll 3d6 for each of the six abilities, in the SRD's order: STR, INT, WIS, DEX, CON, CHA.
This is the first step of creating a character one step at a time. Show the result to the
player, then pass the scores to
validate_class_choice to find out which
classes they qualify for. If the player wants to trade points between abilities after choosing
a class, check the trade with validate_adjustment
and apply it with apply_adjustment.
Call create_character instead when the choices are
already known and you want only the finished character.
The same stream at the same position always gives the same six scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
RngStream
|
The stream to draw from, usually |
required |
Returns:
| Type | Description |
|---|---|
AbilityScoreRolls
|
The six scores and the three dice behind each. |
Examples:
from osrlib.core.character import CHARACTER_CREATION_STREAM, roll_ability_scores
from osrlib.core.rng import RngStreams
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
rolled = roll_ability_scores(stream)
print({ability.value: score for ability, score in rolled.scores.items()})
# {'str': 14, 'int': 6, 'wis': 9, 'dex': 10, 'con': 11, 'cha': 11}
roll_hit_points
roll_hit_points(definition: ClassDefinition, con_modifier: int, ruleset: Ruleset, stream: RngStream) -> HitPointRoll
Roll a first-level character's hit points: the class's hit die plus the CON modifier, and at least 1.
Call it after the class is chosen and the scores are adjusted, so the CON modifier you pass is
the final one. Get the modifier from
load_ability_tables().hit_point_modifier(score). Use the
result's hit_points as the new character's max_hp and current_hp.
This function is for first level only, and it's the only one that applies the
hp_reroll_at_first_level option. For the hit points a character gains at later levels, use
level_up.
With hp_reroll_at_first_level on in the ruleset, this function throws a die that shows 1 or 2
again until it shows 3 or more. The test is on the die before the CON modifier, and the result
includes every throw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The character's class. Its first-level progression row gives the hit die. |
required |
con_modifier
|
int
|
The CON hit point modifier for the final scores. It may be negative, and the hit points are at least 1 either way. |
required |
ruleset
|
Ruleset
|
The ruleset in play, read for the |
required |
stream
|
RngStream
|
The stream to draw from, usually |
required |
Returns:
| Type | Description |
|---|---|
HitPointRoll
|
Every die thrown, and the hit points the character starts with. |
Examples:
from osrlib.core.character import CHARACTER_CREATION_STREAM, roll_hit_points
from osrlib.core.rng import RngStreams
from osrlib.core.ruleset import Ruleset
from osrlib.data import load_classes
fighter = load_classes().get("fighter")
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
print(roll_hit_points(fighter, 0, Ruleset(), stream))
# rolls=(2,) hit_points=2
rerolling = Ruleset(hp_reroll_at_first_level=True)
stream = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
print(roll_hit_points(fighter, 0, rerolling, stream))
# rolls=(2, 8) hit_points=8
roll_starting_gold
roll_starting_gold(stream: RngStream) -> RollResult
Roll a new character's starting money: 3d6 × 10 gold pieces.
This is the last roll of creation. Put the total in the character's purse,
character.inventory.purse.gp. Then buy equipment with it: check each purchase with
validate_purchase and make it with
purchase.
create_character does all of this for you when you
pass purchases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
RngStream
|
The stream to draw from, usually |
required |
Returns:
| Type | Description |
|---|---|
RollResult
|
The roll. Its |
Examples:
validate_class_choice
validate_class_choice(scores: dict[AbilityScore, int], definition: ClassDefinition) -> list[Rejection]
Check whether a set of rolled scores meets a class's minimum ability scores.
Call it after roll_ability_scores and before the
ability adjustment. That's the order the SRD sets: a player picks a class they qualify for, then
trades points. To build the list of classes to offer, call it for each class in
load_classes().classes and keep the ones with no rejections.
It returns rejections rather than raising, so you can show a player why a class is closed to
them. Each rejection's params include the ability, the minimum the class requires, and the
score that fell short. Among the built-in classes, only the demi-humans have requirements: the
dwarf and the halfling require CON 9, the elf requires INT 9, and the halfling also requires
DEX 9.
For the built-in classes, checking before the adjustment is enough. The adjustment can lower only STR, INT, and WIS, never below 9, and no built-in requirement is above 9. If you write a class with a minimum above 9 in STR, INT, or WIS, check the scores again after the adjustment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
dict[AbilityScore, int]
|
The rolled scores, before any adjustment, with all six abilities present. |
required |
definition
|
ClassDefinition
|
The class the player chose, from
|
required |
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
One |
Examples:
from osrlib.core.abilities import AbilityScore
from osrlib.core.character import validate_class_choice
from osrlib.data import load_classes
scores = dict.fromkeys(AbilityScore, 12)
scores[AbilityScore.CON] = 7
rejections = validate_class_choice(scores, load_classes().get("dwarf"))
print([(rejection.code, rejection.params) for rejection in rejections])
# [('creation.class.requirements_not_met', {'class': 'dwarf', 'ability': 'con', 'minimum': 9, 'score': 7})]
print(validate_class_choice(scores, load_classes().get("fighter")))
# []
validate_extra_languages
validate_extra_languages(definition: ClassDefinition, int_score: int, choices: Sequence[str]) -> list[Rejection]
Check the extra languages a character with a high INT chooses.
Every character speaks their alignment tongue and the languages their class grants. An INT of
13 or more allows one to three extra languages, and an INT of 12 or less allows none. To find
out how many a player may choose, call
load_ability_tables().additional_languages(int_score).
Offer the languages whose choosable is True in
load_languages, check the choices here, then store them in
extra_languages.
This function rejects a choice when it isn't a choosable language, when it repeats another choice, or when the class already grants it. Each of these rejections includes the language, so you can show the player which choice to change. If the player chooses more languages than the INT allows, you get one rejection for the whole list, with the number allowed and the number chosen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The chosen class. The languages it grants can't be chosen again as extras. |
required |
int_score
|
int
|
The final INT score, after any adjustment. |
required |
choices
|
Sequence[str]
|
The chosen language ids, from |
required |
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
One |
Examples:
from osrlib.core.character import validate_extra_languages
from osrlib.data import load_ability_tables, load_classes
fighter = load_classes().get("fighter")
print(load_ability_tables().additional_languages(13))
# 1
print(validate_extra_languages(fighter, 13, ["elvish"]))
# []
rejections = validate_extra_languages(fighter, 9, ["elvish"])
print([(rejection.code, rejection.params) for rejection in rejections])
# [('creation.languages.too_many', {'allowed': 0, 'chosen': 1})]
validate_starting_spells
validate_starting_spells(
definition: ClassDefinition, catalog: SpellCatalog, spell_ids: Sequence[str]
) -> list[Rejection]
Check the spells chosen for an arcane caster's starting spell book.
An arcane caster, which among the built-in classes means the magic-user and the elf, starts with
as many spells in their book as they can memorize. At first level that's exactly one
first-level spell. To offer the player the first-level spells on their class's list, pass the
spell_list from caster_profile and the level 1 to
SpellCatalog.by_list. Check the choice here, then
write it with choose_starting_spells. Whether the
player or the referee chooses is up to you. This function only checks the choice.
This function rejects a choice when the spell id is unknown, when it repeats, when the spell is on another class's list, or when the number of spells at any spell level doesn't match the book's size at that level. It rejects too few as well as too many, because the SRD gives a starting book a fixed size. A cleric has no spell book, because clerics receive their spells from a deity, so it rejects any choice for a cleric or for a class that casts no spells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
ClassDefinition
|
The character's class. |
required |
catalog
|
SpellCatalog
|
The spell catalog from |
required |
spell_ids
|
Sequence[str]
|
The chosen spell ids, from |
required |
Returns:
| Type | Description |
|---|---|
list[Rejection]
|
One |
Examples:
from osrlib.core.character import validate_starting_spells
from osrlib.data import load_classes, load_spells
catalog = load_spells()
magic_user = load_classes().get("magic_user")
print(validate_starting_spells(magic_user, catalog, ["sleep"]))
# []
rejections = validate_starting_spells(magic_user, catalog, ["sleep", "magic_missile"])
print([(rejection.code, rejection.params) for rejection in rejections])
# [('magic.book.capacity_mismatch', {'spell_level': 1, 'capacity': 1, 'chosen': 2})]
cleric = load_classes().get("cleric")
print([rejection.code for rejection in validate_starting_spells(cleric, catalog, ["cure_light_wounds"])])
# ['magic.book.not_arcane']