From 7c2d6fc424baabcfe0c3291290f87533a126c9a3 Mon Sep 17 00:00:00 2001 From: Marsh Macy Date: Thu, 26 Nov 2026 07:30:15 -0800 Subject: [PATCH 1/4] Add the contract and acceptance tests for the character creation house rules The new names are stubs with defaults and their final docstrings: `Ruleset.ability_score_method` ("3d6" or "4d6_drop_lowest") and `Ruleset.max_hp_at_first_level`, the `method` keyword of `roll_ability_scores`, `AbilityScoreRolls.dropped`, and `HitPointRoll.maximized` (#341). The `Ruleset` docstrings and the ruleset options guide name house rules as a third kind of flag, which the SRD doesn't print and `Ruleset()` leaves off. examples/rulesets/creation_house_rules.json is a ruleset document with both house rules on and every other field written out at its default, with a README beside it, and the guide includes the file through pymdownx.snippets. tests/test_creation_house_rules.py marks the behaviour tests xfail until the creation-house-rules chunk lands. Its unmarked tests pin that the 3d6 method and the default options draw and give what osrlib 2.8.0 did, and that a save and a creation result that 2.8.0 wrote, kept under tests/saves/, still load. The roll_hit_points example's output comments show the new field. No golden file changes. Claude-Session: https://claude.ai/code/session_01V7Ertq3gKJ46oFQD6635f3 --- docs/guides/ruleset-options.md | 32 +- examples/rulesets/README.md | 20 + examples/rulesets/creation_house_rules.json | 18 + src/osrlib/core/character.py | 82 ++- src/osrlib/core/ruleset.py | 52 +- .../creation_house_rules_result_2.8.0.json | 103 ++++ .../creation_house_rules_save_2.8.0.json | 179 +++++++ tests/test_creation_house_rules.py | 490 ++++++++++++++++++ 8 files changed, 946 insertions(+), 30 deletions(-) create mode 100644 examples/rulesets/README.md create mode 100644 examples/rulesets/creation_house_rules.json create mode 100644 tests/saves/creation_house_rules_result_2.8.0.json create mode 100644 tests/saves/creation_house_rules_save_2.8.0.json create mode 100644 tests/test_creation_house_rules.py diff --git a/docs/guides/ruleset-options.md b/docs/guides/ruleset-options.md index d3fbff8..496e6f1 100644 --- a/docs/guides/ruleset-options.md +++ b/docs/guides/ruleset-options.md @@ -1,10 +1,10 @@ # Ruleset options -Configure optional B/X rules and referee adaptations by constructing a [`Ruleset`][osrlib.core.ruleset.Ruleset] and passing it to [`GameSession.new`][osrlib.crawl.session.GameSession.new] or to standalone `osrlib.core` functions. `Ruleset` is frozen (`extra="forbid"`), persists in saves and replays, and raises Pydantic's `ValidationError` if you pass an unrecognized flag name. +Configure optional B/X rules, referee adaptations, and house rules by constructing a [`Ruleset`][osrlib.core.ruleset.Ruleset] and passing it to [`GameSession.new`][osrlib.crawl.session.GameSession.new] or to standalone `osrlib.core` functions. `Ruleset` is frozen (`extra="forbid"`), persists in saves and replays, and raises Pydantic's `ValidationError` if you pass an unrecognized flag name. ## Construct a `Ruleset` -Call `Ruleset()` with no arguments for the default B/X configuration, or override specific flags such as [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] to change how functions such as [`Character.movement_rate`][osrlib.core.character.Character.movement_rate] behave: +Call `Ruleset()` with no arguments for the default B/X configuration, the SRD as written with no house rule on, or override specific flags such as [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] to change how functions such as [`Character.movement_rate`][osrlib.core.character.Character.movement_rate] behave: ```python from pydantic import ValidationError @@ -61,11 +61,13 @@ else: ## Quick reference -Every `Ruleset` field falls into one of two categories: optional rules printed in the OSE SRD alongside standard B/X procedures, or documented adaptations that supply a deterministic rule where tabletop B/X leaves a judgment call to a human referee (see [the adaptations register](../adaptations.md)): +Every `Ruleset` field falls into one of three categories: optional rules printed in the OSE SRD alongside standard B/X procedures, documented adaptations that supply a deterministic rule where tabletop B/X leaves a judgment call to a human referee (see [the adaptations register](../adaptations.md)), or house rules, which the SRD doesn't print and which `Ruleset()` leaves off: | Flag | Kind | Type and default | Effect | | --- | --- | --- | --- | | `hp_reroll_at_first_level` | Optional rule | `bool`, `False` | Reroll a 1st-level Hit Die when the raw roll is 1 or 2. | +| `max_hp_at_first_level` | House rule | `bool`, `False` | Count a 1st-level Hit Die as its maximum, without changing the dice thrown. | +| `ability_score_method` | House rule | `"3d6" \| "4d6_drop_lowest"`, `"3d6"` | Roll each new character's ability scores as 3d6, or as 4d6 with the lowest die dropped. | | `encumbrance` | Optional rule | `EncumbranceMode`, `BASIC` | Select which encumbrance rule tracks carried weight and movement rate. | | `variable_weapon_damage` | Optional rule | `bool`, `True` | Roll each weapon or combat-gear item's listed damage die instead of a flat `1d6`. | | `individual_initiative` | Optional rule | `bool`, `False` | Roll `1d6` initiative per combatant instead of once per side. | @@ -104,6 +106,30 @@ These options govern rules where tabletop B/X leaves the outcome to referee judg - **`failed_trap_removal_springs`** (`True` by default): When `True`, a thief who fails [`RemoveTreasureTrap`][osrlib.crawl.commands.RemoveTreasureTrap] immediately springs the trap on themselves. When `False`, a failed attempt emits [`TrapEvent`][osrlib.crawl.events.TrapEvent] (`exploration.trap.removal_failed`) and leaves the discovered trap armed: that thief cannot retry, another thief may try, and taking the treasure still has a 2-in-6 chance to spring the trap. - **`back_stab_needs_both_skills`** (`True` by default): A thief who hides during a battle, with a [`BattleDeclaration`][osrlib.crawl.commands.BattleDeclaration] whose `action` is `hide`, can back-stab from hiding. The session rolls hide in shadows when the hide resolves and move silently when the back-stab comes up, and only the referee sees either roll. When `True`, the attack is a back-stab only when both rolls passed. When `False`, either roll passing is enough. The session makes both rolls under either setting, so the flag changes no draw, and the monsters' choice of targets reads the hide in shadows roll alone under either setting. At first level, where hide in shadows is 10% and move silently 20%, a thief's attack from hiding is a back-stab 2% of the time with the flag on and 28% with it off. At seventh level, where they're 45% and 55%, it's about 25% and about 75%. Neither setting is the rules as written, as [the adaptations register](../adaptations.md#a-back-stab-needs-surprised-monsters-or-a-hiding-thief) explains. +## House rules + +These options change character creation in ways the OSE SRD doesn't print. `Ruleset()` leaves both off, so a game uses them only when you turn them on: + +- **`ability_score_method`** (`"3d6"` by default): With `"3d6"`, each ability score is the sum of three d6, as the SRD says. With `"4d6_drop_lowest"`, each ability throws four d6 and the lowest one doesn't count. When two or more tie for lowest, the first of them thrown is dropped. [`AbilityScoreRolls.rolls`][osrlib.core.character.AbilityScoreRolls.rolls] keeps the three dice that count, and [`AbilityScoreRolls.dropped`][osrlib.core.character.AbilityScoreRolls.dropped] has the dropped die of each ability, so a client can show all four. The method draws 24 dice from the creation stream instead of 18, so the same seed gives different scores and a different character. NPC adventurers always roll 3d6. +- **`max_hp_at_first_level`** (`False` by default): When `True`, a first-level character's hit points are the class's hit die at its maximum plus the CON modifier, and at least 1, and [`HitPointRoll.maximized`][osrlib.core.character.HitPointRoll.maximized] is `True`. The hit die is still thrown, and so are the rerolls of `hp_reroll_at_first_level`, so the starting gold roll after them is the same either way. Later levels roll their hit dice as usual. + +`examples/rulesets/creation_house_rules.json` in the osrlib repository is a ruleset document with both house rules on and every other field at its default. It writes out every field, so a copy shows the whole ruleset: + +```json +--8<-- "examples/rulesets/creation_house_rules.json" +``` + +Load it with [`Ruleset.model_validate_json`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_validate_json), and pass the result wherever you'd pass a `Ruleset`: + +```{.python .no-run} +from pathlib import Path + +from osrlib.core.ruleset import Ruleset + +rules = Ruleset.model_validate_json(Path("examples/rulesets/creation_house_rules.json").read_text(encoding="utf-8")) +assert rules == Ruleset(ability_score_method="4d6_drop_lowest", max_hp_at_first_level=True) +``` + ## Where next - [The adaptations register](../adaptations.md) - rule citations and design rationale for each documented adaptation and settled SRD ambiguity. diff --git a/examples/rulesets/README.md b/examples/rulesets/README.md new file mode 100644 index 0000000..e40077e --- /dev/null +++ b/examples/rulesets/README.md @@ -0,0 +1,20 @@ +# Example rulesets + +Each JSON file here is a whole [`Ruleset`](https://mmacy.github.io/osrlib-python/guides/ruleset-options/), with every field written out, so a copy shows every rule a game can change. + +## Creation house rules + +`creation_house_rules.json` turns on two house rules for character creation, so it's not the SRD as written. Neither rule is in the SRD, and `Ruleset()` leaves both off: + +- `ability_score_method` is `"4d6_drop_lowest"`, so each ability score is the sum of the highest three of four d6 instead of 3d6. +- `max_hp_at_first_level` is `true`, so a first-level character's hit die counts as its maximum, plus the CON modifier. + +Every other field has the value `Ruleset()` gives it. To use the ruleset, load the file and pass the result where you'd pass a `Ruleset`, such as to `create_character` and `GameSession.new`: + +```python +from pathlib import Path + +from osrlib.core.ruleset import Ruleset + +rules = Ruleset.model_validate_json(Path("examples/rulesets/creation_house_rules.json").read_text(encoding="utf-8")) +``` diff --git a/examples/rulesets/creation_house_rules.json b/examples/rulesets/creation_house_rules.json new file mode 100644 index 0000000..f291925 --- /dev/null +++ b/examples/rulesets/creation_house_rules.json @@ -0,0 +1,18 @@ +{ + "hp_reroll_at_first_level": false, + "max_hp_at_first_level": true, + "ability_score_method": "4d6_drop_lowest", + "encumbrance": "basic", + "variable_weapon_damage": true, + "individual_initiative": false, + "thac0_arithmetic": false, + "weapon_reload": false, + "hd5_counts_as_magical": false, + "magic_item_death_save": true, + "xp_award_timing": "on_return", + "deprivation_penalties": false, + "aoe_friendly_fire": true, + "formation_width_limit": true, + "failed_trap_removal_springs": true, + "back_stab_needs_both_skills": true +} diff --git a/src/osrlib/core/character.py b/src/osrlib/core/character.py index 2f403a9..5ce69fc 100644 --- a/src/osrlib/core/character.py +++ b/src/osrlib/core/character.py @@ -86,7 +86,7 @@ """ from collections.abc import Mapping, Sequence -from typing import Final +from typing import Final, Literal from pydantic import ConfigDict, Field, field_validator, model_validator @@ -978,12 +978,25 @@ class AbilityScoreRolls(_Model): model_config = ConfigDict(frozen=True) scores: dict[AbilityScore, int] - """The total of each ability's three dice, keyed by [`AbilityScore`][osrlib.core.abilities.AbilityScore]. All six - abilities are present, each from 3 to 18. + """The total of each ability's three counted dice, keyed by [`AbilityScore`][osrlib.core.abilities.AbilityScore]. + All six abilities are present, each from 3 to 18. """ rolls: dict[AbilityScore, tuple[int, int, int]] - """The three d6 results behind each score, keyed the same way, in the order they were rolled.""" + """The three d6 results that count towards each score, keyed the same way, in the order they were thrown. + + Each score is the sum of its three dice. With the `"4d6_drop_lowest"` method, the die dropped + from an ability's four is in `dropped` instead, and the other three keep their order here. + """ + + dropped: dict[AbilityScore, int] = {} + """The die that didn't count towards each score, keyed the same way. + + A `"4d6_drop_lowest"` roll has an entry for all six abilities: the lowest of the four dice, or the + first of them thrown when two or more tie for lowest. A `"3d6"` roll drops nothing, so this is + empty, and so is a roll that osrlib 2.8.0 or earlier recorded. Read an ability with no entry as one + with no die dropped. To show all four dice of an ability, show its three `rolls` and this die. + """ class HitPointRoll(_Model): @@ -1000,11 +1013,23 @@ class HitPointRoll(_Model): """Every die result, before the CON modifier, in the order thrown. With the `hp_reroll_at_first_level` option of [`Ruleset`][osrlib.core.ruleset.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. + thrown again are here too, and the last entry is the die that counts. Otherwise there's one entry. The + `max_hp_at_first_level` option doesn't change what's thrown, so with both options on, the 1s and 2s set aside and + the last die are all here, and `maximized` says the hit points come from the die's size instead. """ hit_points: int = Field(ge=1) - """The hit points the character starts with: the last die plus the CON modifier, and at least 1.""" + """The hit points the character starts with, and at least 1. + + They're the last die plus the CON modifier, or with `maximized` true, the hit die's size plus the CON modifier. + """ + + maximized: bool = False + """Whether the hit die counted as its maximum, because `max_hp_at_first_level` was on in the ruleset. + + When it's true, `hit_points` is the die's size plus the CON modifier, whatever the last entry of `rolls` shows, so + a client can say why. It's false for a roll that osrlib 2.8.0 or earlier recorded. + """ class CharacterCreationResult(_Model): @@ -1035,8 +1060,8 @@ class CharacterCreationResult(_Model): """ -def 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. +def roll_ability_scores(stream: RngStream, *, method: Literal["3d6", "4d6_drop_lowest"] = "3d6") -> AbilityScoreRolls: + """Roll the six ability scores, 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 @@ -1046,16 +1071,31 @@ def roll_ability_scores(stream: RngStream) -> AbilityScoreRolls: and apply it with [`apply_adjustment`][osrlib.core.abilities.apply_adjustment]. Call [`create_character`][osrlib.core.character.create_character] instead when the choices are - already known and you want only the finished character. + already known and you want only the finished character. It passes the `ability_score_method` of + its ruleset as `method`. + + With `"3d6"`, the SRD's method, each ability throws three d6 and the score is their sum. With + `"4d6_drop_lowest"`, a house rule that the SRD doesn't print, each ability throws four d6 and the + lowest one doesn't count. When two or more of the four tie for lowest, the first of them thrown is + the one dropped. The result's `rolls` keeps the three dice that count, in the order thrown, and + `dropped` has the one that doesn't. - The same stream at the same position always gives the same six scores. + The same stream at the same position and the same method always give the same six scores. Args: stream: The stream to draw from, usually `streams.get(CHARACTER_CREATION_STREAM)`. It - advances by 18 dice. + advances by 18 dice with `"3d6"` and by 24 with `"4d6_drop_lowest"`, all of them for + STR before any for INT, and so on. + method: How to roll each score: `"3d6"` or `"4d6_drop_lowest"`. Store it beside a seed if + you roll the same scores again later, because the two methods give different scores from + the same stream. Returns: - The six scores and the three dice behind each. + The six scores, the three dice that count towards each, and any die dropped. + + Raises: + ValueError: If `method` is neither `"3d6"` nor `"4d6_drop_lowest"`. The function checks it + before the first draw, so the stream doesn't advance. Examples: ```python @@ -1149,11 +1189,17 @@ def roll_hit_points( again until it shows 3 or more. The test is on the die before the CON modifier, and the result includes every throw. + With `max_hp_at_first_level` on, a house rule that the SRD doesn't print, the hit points are the + die's size plus the CON modifier, and at least 1, and the result's `maximized` is true. The + function still throws exactly the dice it throws with the option off, so the stream ends in the + same place, and `hp_reroll_at_first_level` changes only what `rolls` lists, never the hit points. + Args: definition: The character's class. Its first-level progression row gives the hit die. con_modifier: The CON hit point modifier for the final scores. It may be negative, and the hit points are at least 1 either way. - ruleset: The ruleset in play, read for the `hp_reroll_at_first_level` option. + ruleset: The ruleset in play, read for the `hp_reroll_at_first_level` and + `max_hp_at_first_level` options. stream: The stream to draw from, usually `streams.get(CHARACTER_CREATION_STREAM)`. Returns: @@ -1169,12 +1215,12 @@ def roll_hit_points( 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 + # rolls=(2,) hit_points=2 maximized=False 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 + # rolls=(2, 8) hit_points=8 maximized=False ``` """ die = definition.row(1).hit_dice.die @@ -1493,8 +1539,10 @@ def create_character( index](https://mmacy.github.io/osrlib-python/reference/content-ids/classes/). For a class you wrote, it's the `id` of `custom_class`. alignment: Lawful, neutral, or chaotic. - ruleset: The ruleset in play. When its `hp_reroll_at_first_level` flag is on, a hit die - showing 1 or 2 is thrown again. + ruleset: The ruleset in play. Its `ability_score_method` sets how the scores are rolled. + When its `hp_reroll_at_first_level` flag is on, a hit die showing 1 or 2 is thrown + again. When its `max_hp_at_first_level` flag is on, the hit die counts as its maximum, + and the dice thrown, and so the gold roll after them, stay the same. stream: The stream for the creation draws, usually `streams.get(`[`CHARACTER_CREATION_STREAM`][osrlib.core.character.CHARACTER_CREATION_STREAM]`)`. custom_class: The definition of a class you wrote, or `None` to play a class osrlib diff --git a/src/osrlib/core/ruleset.py b/src/osrlib/core/ruleset.py index ed25346..93b9e34 100644 --- a/src/osrlib/core/ruleset.py +++ b/src/osrlib/core/ruleset.py @@ -8,14 +8,16 @@ call, so there's no setup step. A save contains the ruleset, so a loaded game uses the rules it began with. -`Ruleset()` with no arguments gives you the SRD rules as written. Each flag is either an -optional rule or an adaptation. An optional rule is an alternative the SRD prints beside -its default procedure. An adaptation is a default osrlib chooses for a decision that the -tabletop game leaves to a human referee. A program that runs without a referee has to -make that decision. -The two enum flags, [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] and -[`XpAwardTiming`][osrlib.core.ruleset.XpAwardTiming], pick among alternatives instead of -switching one behavior on and off. +`Ruleset()` with no arguments gives you the SRD rules as written. Each flag is an optional +rule, an adaptation, or a house rule. An optional rule is an alternative the SRD prints +beside its default procedure. An adaptation is a default osrlib chooses for a decision that +the tabletop game leaves to a human referee. A program that runs without a referee has to +make that decision. A house rule changes a procedure in a way the SRD doesn't print, and +it's off unless you turn it on. +Three flags pick among alternatives instead of switching one behavior on and off: the two +enum flags, [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] and +[`XpAwardTiming`][osrlib.core.ruleset.XpAwardTiming], and the string flag +`ability_score_method`. Each flag is a field of [`Ruleset`][osrlib.core.ruleset.Ruleset], documented there and in [the ruleset options guide](https://mmacy.github.io/osrlib-python/guides/ruleset-options/) @@ -44,6 +46,8 @@ # Code reads every flag here. Don't add a flag before the code that reads it exists. # Adding a flag with a default doesn't require a schema_version bump. +from typing import Literal + from pydantic import ConfigDict from osrlib.core._descriptions import _StrEnum @@ -124,10 +128,11 @@ class Ruleset(_Model): unknown field name raises a pydantic `ValidationError`, so a misspelled flag fails instead of doing nothing. - Each flag is one of two kinds. An optional rule is an alternative the SRD prints + Each flag is one of three kinds. An optional rule is an alternative the SRD prints beside its standard procedure, and osrlib's default is the book's. An adaptation is a default osrlib supplies where the tabletop game leaves the decision to a human - referee. [The adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) + referee. A house rule is a change the SRD doesn't print, and its default is the SRD's + procedure. [The adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) gives the reasoning behind each one. Examples: @@ -153,6 +158,33 @@ class Ruleset(_Model): that modifier. """ + max_hp_at_first_level: bool = False + """Count a first-level character's hit die as its maximum. A house rule, off by default. + + The SRD doesn't print this rule. Its character creation has you roll the class's hit die. Turn + the flag on and a first-level character's hit points are the hit die's size plus the CON + modifier, and at least 1, so a fighter with CON 7 starts with 8 - 1 = 7. + [`roll_hit_points`][osrlib.core.character.roll_hit_points] still throws the dice it throws with + the flag off, so the creation stream ends in the same place and the starting gold roll after it is + the same. With `hp_reroll_at_first_level` also on, a die showing 1 or 2 is still thrown again and + [`HitPointRoll.rolls`][osrlib.core.character.HitPointRoll.rolls] lists every die, but the + reroll can't change the hit points. The flag affects only the hit points rolled at character + creation. [`level_up`][osrlib.core.classes.level_up] rolls each later level's hit die as usual. + """ + + ability_score_method: Literal["3d6", "4d6_drop_lowest"] = "3d6" + """How a new character's ability scores are rolled. `"3d6"` by default, the SRD's method. + + `"4d6_drop_lowest"` is a house rule, not an SRD rule. With it, each ability throws four d6 and + the lowest die doesn't count, so the score is the sum of the other three, from 3 to 18. + [`create_character`][osrlib.core.character.create_character] passes the method to + [`roll_ability_scores`][osrlib.core.character.roll_ability_scores], and the result lists the + dropped die of each ability in + [`AbilityScoreRolls.dropped`][osrlib.core.character.AbilityScoreRolls.dropped]. The method + affects only the characters you create. The NPC adventurers that encounters generate always + roll 3d6. + """ + encumbrance: EncumbranceMode = EncumbranceMode.BASIC """Which system tracks carried weight and sets movement rate. Basic by default. diff --git a/tests/saves/creation_house_rules_result_2.8.0.json b/tests/saves/creation_house_rules_result_2.8.0.json new file mode 100644 index 0000000..b490385 --- /dev/null +++ b/tests/saves/creation_house_rules_result_2.8.0.json @@ -0,0 +1,103 @@ +{ + "ability_rolls": { + "rolls": { + "cha": [ + 3, + 6, + 2 + ], + "con": [ + 3, + 6, + 2 + ], + "dex": [ + 2, + 2, + 6 + ], + "int": [ + 4, + 1, + 1 + ], + "str": [ + 2, + 6, + 6 + ], + "wis": [ + 3, + 5, + 1 + ] + }, + "scores": { + "cha": 11, + "con": 11, + "dex": 10, + "int": 6, + "str": 14, + "wis": 9 + } + }, + "character": { + "alignment": "neutral", + "carrying_treasure": false, + "class_id": "thief", + "conditions": [], + "current_hp": 3, + "custom_class": null, + "extra_languages": [], + "id": "character-0001", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 60, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 1, + "max_hp": 3, + "memorized_spells": [], + "name": "Wren", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 11, + "con": 11, + "dex": 10, + "int": 6, + "str": 14, + "wis": 9 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 0 + }, + "gold_roll": { + "modifier": 0, + "multiplier": 10, + "rolls": [ + 3, + 2, + 1 + ], + "total": 60 + }, + "hit_point_roll": { + "hit_points": 3, + "rolls": [ + 2, + 3 + ] + } +} diff --git a/tests/saves/creation_house_rules_save_2.8.0.json b/tests/saves/creation_house_rules_save_2.8.0.json new file mode 100644 index 0000000..c50dda0 --- /dev/null +++ b/tests/saves/creation_house_rules_save_2.8.0.json @@ -0,0 +1,179 @@ +{ + "engine_version": "2.8.0", + "kind": "save", + "payload": { + "adventure": { + "description": "", + "dungeons": [ + { + "id": "crypt", + "levels": [ + { + "areas": [], + "edges": {}, + "entrance": [ + 0, + 0 + ], + "features": [], + "guidance": "", + "height": 1, + "number": 1, + "transitions": [], + "wandering": { + "chance_in_six": 1, + "interval_turns": 2, + "table": null + }, + "width": 1 + } + ], + "name": "The Crypt" + } + ], + "hooks": [], + "items": [], + "monsters": [], + "name": "A Delve", + "party": null, + "quests": [], + "spells": [], + "town": { + "description": "", + "healing_prices": {}, + "name": "Threshold", + "services": [], + "travel_turns": {} + }, + "triggers": [] + }, + "allocator": { + "counters": { + "character": 1 + } + }, + "battle": null, + "clock_rounds": 0, + "command_log": [], + "death_records": {}, + "defeated_monsters": [], + "deprivation": {}, + "dungeon_state": { + "doors": {}, + "emptied_caches": [], + "explored": {}, + "found_traps": [], + "found_tricks": [], + "generated_caches": {}, + "generated_lair_hoards": [], + "generated_treasure_areas": [], + "inspect_attempts": {}, + "listen_attempts": {}, + "location": { + "dungeon_id": null, + "facing": null, + "kind": "town", + "level_number": null, + "position": null + }, + "lock_failures": {}, + "piles": {}, + "removal_attempts": {}, + "removed_traps": [], + "resolved_encounters": [], + "search_attempts": {}, + "seen": {}, + "sprung_traps": [] + }, + "encounter": null, + "event_log": [], + "exploration": { + "alerted_areas": [], + "heard_areas": [], + "last_prepared_sleep": {}, + "noise_since_check": false, + "odometer_thirds": 0, + "provisions_day": 0, + "sleep_count": 0, + "turns_since_rest": 0, + "wandering_counter": 0 + }, + "fired_triggers": [], + "flags": {}, + "journal": [], + "ledger": { + "effects": [] + }, + "listener_state": {}, + "master_seed": 7, + "mode": "town", + "monsters": [], + "npcs": [], + "party": { + "members": [ + { + "alignment": "neutral", + "carrying_treasure": false, + "class_id": "thief", + "conditions": [], + "current_hp": 3, + "custom_class": null, + "extra_languages": [], + "id": "character-0001", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 60, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 1, + "max_hp": 3, + "memorized_spells": [], + "name": "Wren", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 11, + "con": 11, + "dex": 10, + "int": 6, + "str": 14, + "wis": 9 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 0 + } + ] + }, + "quests": {}, + "rng_streams": {}, + "ruleset": { + "aoe_friendly_fire": true, + "back_stab_needs_both_skills": true, + "deprivation_penalties": false, + "encumbrance": "basic", + "failed_trap_removal_springs": true, + "formation_width_limit": true, + "hd5_counts_as_magical": false, + "hp_reroll_at_first_level": true, + "individual_initiative": false, + "magic_item_death_save": true, + "thac0_arithmetic": false, + "variable_weapon_damage": true, + "weapon_reload": false, + "xp_award_timing": "on_return" + }, + "treasure_snapshot_cp": null + }, + "schema_version": 4 +} diff --git a/tests/test_creation_house_rules.py b/tests/test_creation_house_rules.py new file mode 100644 index 0000000..e5d5cc8 --- /dev/null +++ b/tests/test_creation_house_rules.py @@ -0,0 +1,490 @@ +"""Acceptance tests for the two house rules of character creation (#341). + +`Ruleset.ability_score_method` picks 3d6 or 4d6 drop lowest for the ability scores, and +`Ruleset.max_hp_at_first_level` counts the first-level hit die as its maximum. Both are off by +default. The tests marked `chunk: creation-house-rules` wait for the implementation. The unmarked +ones hold the contract that the default rules draw and give exactly what osrlib 2.8.0 drew and gave, +and that what 2.8.0 wrote still loads. Their literal values were computed by running the 2.8.0 +source from `git archive v2.8.0` on the creation stream of each seed. + +Every die on the creation stream is one `randbelow(sides) + 1` draw, so a replayed stream gives the +dice each test derives its numbers from. +""" + +import json +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from osrlib.core.abilities import AbilityScore +from osrlib.core.alignment import Alignment +from osrlib.core.character import ( + ABILITY_ROLL_ORDER, + CHARACTER_CREATION_STREAM, + CharacterCreationResult, + create_character, + roll_ability_scores, + roll_hit_points, +) +from osrlib.core.rng import RngStream, RngStreams +from osrlib.core.ruleset import Ruleset +from osrlib.data import load_classes +from osrlib.persistence import load_game + +CHUNK = "chunk: creation-house-rules" + +SAVES = Path(__file__).parent / "saves" +SAVE_2_8_0 = SAVES / "creation_house_rules_save_2.8.0.json" +"""A save that osrlib 2.8.0 wrote, kept as written. + +Its party is one thief, Wren, created from seed 7 with `hp_reroll_at_first_level` on: rolls (2, 3) +and 3 hit points. Its ruleset has that one flag on. +""" +RESULT_2_8_0 = SAVES / "creation_house_rules_result_2.8.0.json" +"""The `CharacterCreationResult` behind Wren, as 2.8.0 dumped it with `model_dump(mode="json")`.""" + +REPO = Path(__file__).resolve().parent.parent +CHANGELOG = REPO / "CHANGELOG.md" +EXAMPLE = REPO / "examples" / "rulesets" / "creation_house_rules.json" +"""The example ruleset document: the SRD ruleset with both creation house rules on.""" + +STR, INT, WIS, DEX, CON, CHA = ABILITY_ROLL_ORDER + + +def stream(seed: int) -> RngStream: + return RngStreams(master_seed=seed).get(CHARACTER_CREATION_STREAM) + + +def d6_draws(seed: int, count: int) -> tuple[RngStream, list[int]]: + """Replay `count` d6 draws from the seed's creation stream, and return the stream after them.""" + replay = stream(seed) + return replay, [replay.randbelow(6) + 1 for _ in range(count)] + + +def by_ability(values: list) -> dict[AbilityScore, object]: + return dict(zip(ABILITY_ROLL_ORDER, values, strict=True)) + + +def create(seed: int, class_id: str, ruleset: Ruleset) -> tuple[CharacterCreationResult, RngStream]: + creation = stream(seed) + result = create_character( + name="Wren", class_id=class_id, alignment=Alignment.NEUTRAL, ruleset=ruleset, stream=creation + ) + return result, creation + + +# ---------------------------------------------------------------------- 3d6 is what 2.8.0 drew + +# seed -> (scores, dice, the stream's next_uint64 after the roll), from the 2.8.0 source. +ABILITY_ROLLS_2_8_0 = { + 1: ( + [12, 13, 12, 8, 12, 8], + [(4, 6, 2), (3, 5, 5), (3, 6, 3), (1, 5, 2), (2, 6, 4), (1, 3, 4)], + 10764926779193130477, + ), + 2: ( + [10, 9, 10, 15, 13, 9], + [(5, 1, 4), (1, 6, 2), (2, 6, 2), (4, 5, 6), (5, 4, 4), (4, 2, 3)], + 14761271966634835755, + ), + 7: ( + [14, 6, 9, 10, 11, 11], + [(2, 6, 6), (4, 1, 1), (3, 5, 1), (2, 2, 6), (3, 6, 2), (3, 6, 2)], + 5227041208467167983, + ), + 11: ( + [7, 11, 9, 8, 17, 14], + [(3, 1, 3), (4, 2, 5), (2, 4, 3), (1, 2, 5), (6, 5, 6), (6, 6, 2)], + 5439222053352104398, + ), + 42: ( + [10, 12, 15, 15, 11, 11], + [(2, 4, 4), (6, 4, 2), (5, 5, 5), (5, 5, 5), (3, 3, 5), (5, 1, 5)], + 9990027807474700127, + ), + 2026: ( + [9, 10, 14, 10, 9, 3], + [(3, 1, 5), (2, 4, 4), (4, 5, 5), (5, 3, 2), (6, 2, 1), (1, 1, 1)], + 12013198524635192933, + ), +} + + +@pytest.mark.parametrize("seed", sorted(ABILITY_ROLLS_2_8_0)) +def test_3d6_ability_rolls_match_2_8_0(seed): + scores, dice, next_draw = ABILITY_ROLLS_2_8_0[seed] + creation = stream(seed) + + rolled = roll_ability_scores(creation) + + assert rolled.scores == by_ability(scores) + assert rolled.rolls == by_ability(dice) + assert creation.next_uint64() == next_draw + + +@pytest.mark.parametrize("seed", sorted(ABILITY_ROLLS_2_8_0)) +def test_the_3d6_method_named_matches_2_8_0_and_drops_nothing(seed): + scores, dice, next_draw = ABILITY_ROLLS_2_8_0[seed] + creation = stream(seed) + + rolled = roll_ability_scores(creation, method="3d6") + + assert rolled.scores == by_ability(scores) + assert rolled.rolls == by_ability(dice) + assert rolled.dropped == {} + assert creation.next_uint64() == next_draw + + +# (seed, class, hp_reroll_at_first_level) -> (scores, hit dice, hit points, gold dice, gold, next_uint64), +# from the 2.8.0 source. +CREATED_2_8_0 = { + (2, "fighter", False): ([10, 9, 10, 15, 13, 9], (7,), 8, (2, 1, 3), 60, 17037473347644245223), + (7, "thief", True): ([14, 6, 9, 10, 11, 11], (2, 3), 3, (3, 2, 1), 60, 15955583499778908635), + (42, "cleric", False): ([10, 12, 15, 15, 11, 11], (5,), 5, (6, 2, 6), 140, 11020725460617047001), +} + + +@pytest.mark.parametrize("case", sorted(CREATED_2_8_0)) +def test_3d6_create_character_matches_2_8_0(case): + seed, class_id, reroll = case + scores, hit_dice, hit_points, gold_dice, gold, next_draw = CREATED_2_8_0[case] + + result, creation = create(seed, class_id, Ruleset(hp_reroll_at_first_level=reroll)) + + assert result.ability_rolls.scores == by_ability(scores) + assert result.ability_rolls.rolls == by_ability(ABILITY_ROLLS_2_8_0[seed][1]) + assert result.hit_point_roll.rolls == hit_dice + assert result.hit_point_roll.hit_points == hit_points + assert result.character.max_hp == hit_points + assert result.gold_roll.rolls == gold_dice + assert result.gold_roll.total == gold + assert creation.next_uint64() == next_draw + + +@pytest.mark.parametrize("case", sorted(CREATED_2_8_0)) +def test_the_default_options_named_match_2_8_0(case): + seed, class_id, reroll = case + scores, hit_dice, hit_points, gold_dice, gold, next_draw = CREATED_2_8_0[case] + ruleset = Ruleset(hp_reroll_at_first_level=reroll, ability_score_method="3d6", max_hp_at_first_level=False) + + result, creation = create(seed, class_id, ruleset) + + assert result.ability_rolls.scores == by_ability(scores) + assert result.ability_rolls.dropped == {} + assert result.hit_point_roll.rolls == hit_dice + assert result.hit_point_roll.hit_points == hit_points + assert result.hit_point_roll.maximized is False + assert result.gold_roll.rolls == gold_dice + assert creation.next_uint64() == next_draw + + +def test_both_options_are_off_by_default(): + rules = Ruleset() + assert rules.ability_score_method == "3d6" + assert rules.max_hp_at_first_level is False + + +def test_a_ruleset_refuses_an_unknown_ability_score_method(): + with pytest.raises(ValidationError): + Ruleset(ability_score_method="2d6") # type: ignore[arg-type] + + +# ---------------------------------------------------------------------- what 2.8.0 wrote still loads + + +def test_a_2_8_0_save_loads_with_both_options_off(): + document = json.loads(SAVE_2_8_0.read_text(encoding="utf-8")) + assert document["engine_version"] == "2.8.0" + assert "ability_score_method" not in document["payload"]["ruleset"] + assert "max_hp_at_first_level" not in document["payload"]["ruleset"] + + session = load_game(document) + + assert session.ruleset == Ruleset(hp_reroll_at_first_level=True) + assert session.ruleset.ability_score_method == "3d6" + assert session.ruleset.max_hp_at_first_level is False + (wren,) = session.party.members + assert (wren.name, wren.max_hp) == ("Wren", 3) + + +def test_a_2_8_0_creation_result_parses_with_the_new_fields_at_their_defaults(): + document = json.loads(RESULT_2_8_0.read_text(encoding="utf-8")) + assert "dropped" not in document["ability_rolls"] + assert "maximized" not in document["hit_point_roll"] + + result = CharacterCreationResult.model_validate(document) + + assert result.ability_rolls.dropped == {} + assert result.ability_rolls.rolls[INT] == (4, 1, 1) + assert result.hit_point_roll.maximized is False + assert result.hit_point_roll.rolls == (2, 3) + assert result.hit_point_roll.hit_points == 3 + + +# ---------------------------------------------------------------------- 4d6 drop lowest + +# seed -> (counted dice, dropped die, score) per ability, in STR, INT, WIS, DEX, CON, CHA order. +# +# Each ability takes the next four d6 draws. The lowest die is dropped, and when two or more tie for +# lowest, the first of them thrown is the one dropped. The other three keep their throw order. +FOUR_D6 = { + # Draws: 5 1 4 1 | 6 2 2 6 | 2 4 5 6 | 5 4 4 4 | 2 3 2 1 | 3 2 6 5 + 2: [ + ((5, 4, 1), 1, 10), # 1s tie at throws 2 and 4: the first is dropped, so (5, 4, 1), never (5, 1, 4). + ((6, 2, 6), 2, 14), # 2s tie at throws 2 and 3: dropping the first leaves (6, 2, 6). + ((4, 5, 6), 2, 15), + ((5, 4, 4), 4, 13), # Three 4s tie: the first, at throw 2, is dropped. + ((2, 3, 2), 1, 7), + ((3, 6, 5), 2, 14), + ], + # Draws: 2 6 6 4 | 1 1 3 5 | 1 2 2 6 | 3 6 2 3 | 6 2 3 5 | 3 2 1 5 + 7: [ + ((6, 6, 4), 2, 16), + ((1, 3, 5), 1, 9), + ((2, 2, 6), 1, 10), + ((3, 6, 3), 2, 12), + ((6, 3, 5), 2, 14), + ((3, 2, 5), 1, 10), + ], + # Draws: 2 4 4 6 | 4 2 5 5 | 5 5 5 5 | 3 3 5 5 | 1 5 5 6 | 2 6 5 2 + 42: [ + ((4, 4, 6), 2, 14), + ((4, 5, 5), 2, 14), + ((5, 5, 5), 5, 15), # Four 5s: one 5 is dropped and three count. + ((3, 5, 5), 3, 13), + ((5, 5, 6), 1, 16), + ((6, 5, 2), 2, 13), # 2s tie at throws 1 and 4: the first is dropped, so (6, 5, 2), never (2, 6, 5). + ], +} + + +@pytest.mark.xfail(reason=CHUNK) +@pytest.mark.parametrize("seed", sorted(FOUR_D6)) +def test_4d6_drop_lowest_counts_three_dice_and_names_the_dropped_one(seed): + expected = FOUR_D6[seed] + + rolled = roll_ability_scores(stream(seed), method="4d6_drop_lowest") + + assert rolled.rolls == by_ability([counted for counted, _, _ in expected]) + assert rolled.dropped == by_ability([dropped for _, dropped, _ in expected]) + assert rolled.scores == by_ability([score for _, _, score in expected]) + for ability in ABILITY_ROLL_ORDER: + assert sum(rolled.rolls[ability]) == rolled.scores[ability] + assert rolled.dropped[ability] <= min(rolled.rolls[ability]) + + +@pytest.mark.xfail(reason=CHUNK) +@pytest.mark.parametrize("seed", sorted(FOUR_D6)) +def test_4d6_drop_lowest_throws_the_draws_in_order_and_advances_24_dice(seed): + creation = stream(seed) + + rolled = roll_ability_scores(creation, method="4d6_drop_lowest") + + replay, draws = d6_draws(seed, 24) + for index, ability in enumerate(ABILITY_ROLL_ORDER): + thrown = draws[4 * index : 4 * index + 4] + assert sorted((*rolled.rolls[ability], rolled.dropped[ability])) == sorted(thrown) + assert creation.export_state() == replay.export_state() + + +@pytest.mark.xfail(reason=CHUNK) +def test_4d6_drop_lowest_scores_range_from_3_to_18(): + for seed in range(60): + rolled = roll_ability_scores(stream(seed), method="4d6_drop_lowest") + assert set(rolled.dropped) == set(AbilityScore) + assert all(3 <= score <= 18 for score in rolled.scores.values()) + + +@pytest.mark.xfail(reason=CHUNK) +def test_an_unknown_method_raises_before_the_first_draw(): + creation = stream(7) + before = creation.export_state() + + with pytest.raises(ValueError, match="2d6"): + roll_ability_scores(creation, method="2d6") # type: ignore[arg-type] + + assert creation.export_state() == before + + +@pytest.mark.xfail(reason=CHUNK) +def test_create_character_rolls_with_the_rulesets_method(): + # Seed 2's 4d6 scores, from FOUR_D6, are STR 10, INT 14, WIS 15, DEX 13, CON 7, and CHA 14. After + # the 24 ability dice, the fighter's d8 hit die is draw 25 and shows 6. CON 7 has a -1 hit + # point modifier, so the fighter has 6 - 1 = 5 hit points. The gold dice are draws 26 to 28: 4 2 3, + # 9 × 10 = 90 gold pieces. + result, creation = create(2, "fighter", Ruleset(ability_score_method="4d6_drop_lowest")) + + expected = roll_ability_scores(stream(2), method="4d6_drop_lowest") + assert result.ability_rolls == expected + assert result.ability_rolls.scores == by_ability([10, 14, 15, 13, 7, 14]) + assert result.character.scores == expected.scores + assert result.hit_point_roll.rolls == (6,) + assert result.hit_point_roll.hit_points == 5 + assert result.hit_point_roll.maximized is False + assert result.gold_roll.rolls == (4, 2, 3) + assert result.gold_roll.total == 90 + + replay, _ = d6_draws(2, 24) + assert replay.randbelow(8) + 1 == 6 + assert [replay.randbelow(6) + 1 for _ in range(3)] == [4, 2, 3] + assert creation.export_state() == replay.export_state() + + +# ---------------------------------------------------------------------- maximum hit points at first level + +# Seed 7's thief: the 3d6 scores give CON 11, a hit point modifier of 0. The d4 hit die is draw 19 +# and shows 2. With `hp_reroll_at_first_level` on, the 2 is set aside and draw 20 shows 3. The gold +# dice follow the hit dice: 5 3 2 (100 gp) without the reroll, 3 2 1 (60 gp) with it. +THIEF_HIT_DICE = {False: (2,), True: (2, 3)} +THIEF_GOLD = {False: ((5, 3, 2), 100), True: ((3, 2, 1), 60)} + + +@pytest.mark.xfail(reason=CHUNK) +@pytest.mark.parametrize("reroll", [False, True]) +def test_the_maximum_draws_what_the_roll_draws_so_the_gold_is_the_same(reroll): + rolled, rolled_stream = create(7, "thief", Ruleset(hp_reroll_at_first_level=reroll)) + maximum, maximum_stream = create(7, "thief", Ruleset(hp_reroll_at_first_level=reroll, max_hp_at_first_level=True)) + + assert rolled.hit_point_roll.rolls == maximum.hit_point_roll.rolls == THIEF_HIT_DICE[reroll] + assert rolled.gold_roll == maximum.gold_roll + assert (maximum.gold_roll.rolls, maximum.gold_roll.total) == THIEF_GOLD[reroll] + assert rolled_stream.export_state() == maximum_stream.export_state() + assert rolled.ability_rolls == maximum.ability_rolls + + # The thief's d4 at its maximum, plus CON 11's modifier of 0. + assert maximum.hit_point_roll.hit_points == 4 + assert maximum.character.max_hp == maximum.character.current_hp == 4 + assert maximum.hit_point_roll.maximized is True + assert rolled.hit_point_roll.hit_points == THIEF_HIT_DICE[reroll][-1] + assert rolled.hit_point_roll.maximized is False + + +@pytest.mark.xfail(reason=CHUNK) +def test_with_the_maximum_and_the_reroll_on_the_set_aside_dice_are_still_listed(): + # The reroll still throws: the 2 is set aside and the 3 is the last die. The maximum replaces the + # last die's value in the hit points only, so they're the d4's 4 plus a modifier of 0. + result, _ = create(7, "thief", Ruleset(hp_reroll_at_first_level=True, max_hp_at_first_level=True)) + + assert result.hit_point_roll.rolls == (2, 3) + assert result.hit_point_roll.maximized is True + assert result.hit_point_roll.hit_points == 4 + + +# The first-level hit die of each built-in class, from the Hit Dice row of its SRD page: +# cleric, elf, and halfling 1d6, dwarf and fighter 1d8, magic-user and thief 1d4. +HIT_DIE = {"cleric": 6, "dwarf": 8, "elf": 6, "fighter": 8, "halfling": 6, "magic_user": 4, "thief": 4} + + +@pytest.mark.xfail(reason=CHUNK) +@pytest.mark.parametrize("class_id", sorted(HIT_DIE)) +@pytest.mark.parametrize("con_modifier", [-5, -4, -3, -1, 0, 1, 3]) +def test_the_maximum_is_the_die_size_plus_the_modifier_and_at_least_1(class_id, con_modifier): + # A d4 with -4 or -5 would be 0 or -1, so the floor of 1 holds those to 1. A CON of 3 gives -3, + # and a d4's 4 - 3 is already 1. + definition = load_classes().get(class_id) + assert definition.row(1).hit_dice.die == HIT_DIE[class_id] + for seed in (2, 7, 42): + maximum_stream, rolled_stream = stream(seed), stream(seed) + + maximum = roll_hit_points(definition, con_modifier, Ruleset(max_hp_at_first_level=True), maximum_stream) + rolled = roll_hit_points(definition, con_modifier, Ruleset(), rolled_stream) + + assert maximum.hit_points == max(1, HIT_DIE[class_id] + con_modifier) + assert maximum.maximized is True + assert maximum.rolls == rolled.rolls + assert len(maximum.rolls) == 1 + assert maximum_stream.export_state() == rolled_stream.export_state() + + +# ---------------------------------------------------------------------- both options together + + +@pytest.mark.xfail(reason=CHUNK) +def test_both_options_in_one_create_character_call(): + # The scores and the dice are seed 2's 4d6 drop lowest from FOUR_D6. CON 7 gives -1. The fighter's + # d8 is draw 25, a 6, and the maximum counts it as 8, so the fighter has 8 - 1 = 7 hit points. The + # gold dice are draws 26 to 28, as with the maximum off: 4 2 3, 90 gp. + ruleset = Ruleset(ability_score_method="4d6_drop_lowest", max_hp_at_first_level=True) + + result, creation = create(2, "fighter", ruleset) + + assert result.ability_rolls.rolls == by_ability([counted for counted, _, _ in FOUR_D6[2]]) + assert result.ability_rolls.dropped == by_ability([dropped for _, dropped, _ in FOUR_D6[2]]) + assert result.character.scores == by_ability([10, 14, 15, 13, 7, 14]) + assert result.hit_point_roll.rolls == (6,) + assert result.hit_point_roll.maximized is True + assert result.hit_point_roll.hit_points == 7 + assert result.character.max_hp == 7 + assert (result.gold_roll.rolls, result.gold_roll.total) == ((4, 2, 3), 90) + assert result.character.inventory.purse.gp == 90 + + replay, _ = d6_draws(2, 24) + replay.randbelow(8) + for _ in range(3): + replay.randbelow(6) + assert creation.export_state() == replay.export_state() + + +# ---------------------------------------------------------------------- the example ruleset + +HOUSE_RULES = Ruleset(ability_score_method="4d6_drop_lowest", max_hp_at_first_level=True) + + +def test_the_example_ruleset_loads_as_the_two_house_rules_on(): + rules = Ruleset.model_validate_json(EXAMPLE.read_text(encoding="utf-8")) + + assert rules == HOUSE_RULES + changed = {name for name in Ruleset.model_fields if getattr(rules, name) != getattr(Ruleset(), name)} + assert changed == {"ability_score_method", "max_hp_at_first_level"} + + +def test_the_example_ruleset_writes_out_every_field(): + # A field added to `Ruleset` later fails this test until the example names it too. + document = json.loads(EXAMPLE.read_text(encoding="utf-8")) + + assert set(document) == set(Ruleset.model_fields) + assert document == HOUSE_RULES.model_dump(mode="json") + + +def test_the_guide_includes_the_example_file_itself(): + # pymdownx.snippets puts the file into the page at build time, and its `check_paths` fails the + # strict build if the file is missing, so the page shows the file as it is. + guide = (REPO / "docs" / "guides" / "ruleset-options.md").read_text(encoding="utf-8") + + assert '```json\n--8<-- "examples/rulesets/creation_house_rules.json"\n```' in guide + + +def test_the_example_readme_says_what_the_ruleset_changes_and_how_to_load_it(): + readme = (EXAMPLE.parent / "README.md").read_text(encoding="utf-8") + + for text in ("creation_house_rules.json", "ability_score_method", "max_hp_at_first_level", "model_validate_json"): + assert text in readme + assert "not the SRD" in readme + + +@pytest.mark.xfail(reason=CHUNK) +def test_a_character_created_with_the_example_ruleset_has_4d6_scores_and_the_maximum(): + # The same draws as test_both_options_in_one_create_character_call: seed 2's 4d6 drop lowest + # scores, and the fighter's d8 at its maximum, 8, with CON 7's -1, for 7 hit points. + rules = Ruleset.model_validate_json(EXAMPLE.read_text(encoding="utf-8")) + + result, _ = create(2, "fighter", rules) + + assert result.ability_rolls.dropped == by_ability([dropped for _, dropped, _ in FOUR_D6[2]]) + assert result.character.scores == by_ability([score for _, _, score in FOUR_D6[2]]) + assert result.hit_point_roll.maximized is True + assert result.character.max_hp == 7 + + +# ---------------------------------------------------------------------- the changelog + + +@pytest.mark.xfail(reason=CHUNK) +def test_the_changelog_bullet_names_both_options_and_both_fields(): + bullets = [line for line in CHANGELOG.read_text(encoding="utf-8").splitlines() if "(#341)" in line] + assert len(bullets) == 1 + (bullet,) = bullets + assert bullet.startswith("- ") + for name in ("ability_score_method", "4d6_drop_lowest", "max_hp_at_first_level", "dropped", "maximized"): + assert name in bullet From f7541a4b49ff6fda1d648c464cb45862279f39f3 Mon Sep 17 00:00:00 2001 From: Marsh Macy Date: Thu, 26 Nov 2026 07:35:04 -0800 Subject: [PATCH 2/4] Roll 4d6 drop lowest and maximize the first-level hit die when the ruleset asks roll_ability_scores takes its method keyword: "3d6" rolls as before, and "4d6_drop_lowest" throws four d6 per ability, drops the first of the lowest, and records that die in AbilityScoreRolls.dropped. It refuses an unknown method before its first draw. create_character passes Ruleset.ability_score_method as the method. roll_hit_points throws the same dice whatever max_hp_at_first_level says, and with the flag on counts the hit die's size instead of the last die and sets HitPointRoll.maximized, so the starting gold roll after it is unchanged. With both house rules at their defaults every draw and result is what 2.8.0 gave. No golden file changes. The changelog bullet for #341 goes under Unreleased, Added. Claude-Session: https://claude.ai/code/session_01V7Ertq3gKJ46oFQD6635f3 --- CHANGELOG.md | 4 ++++ src/osrlib/core/character.py | 27 +++++++++++++++++++++------ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 052eef4..7a39e90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added + +- Two house rules for character creation, which the SRD doesn't print and `Ruleset()` leaves off (#341). [`Ruleset.ability_score_method`][osrlib.core.ruleset.Ruleset.ability_score_method] is `"3d6"` by default. With `"4d6_drop_lowest"`, [`create_character`][osrlib.core.character.create_character] throws four d6 for each ability and drops the lowest, the first of them thrown when two or more tie, and [`roll_ability_scores`][osrlib.core.character.roll_ability_scores] does the same when you pass the method to its new `method` keyword. [`AbilityScoreRolls.rolls`][osrlib.core.character.AbilityScoreRolls.rolls] keeps the three dice that count, and the new [`AbilityScoreRolls.dropped`][osrlib.core.character.AbilityScoreRolls.dropped] has the dropped die of each ability, so a client can show all four. The method draws 24 dice instead of 18, so the same seed gives a different character, and NPC adventurers always roll 3d6. With [`Ruleset.max_hp_at_first_level`][osrlib.core.ruleset.Ruleset.max_hp_at_first_level] on, a first-level character's hit points are the hit die's size plus the CON modifier, and at least 1, and the new [`HitPointRoll.maximized`][osrlib.core.character.HitPointRoll.maximized] is true. The hit die and any rerolls of `hp_reroll_at_first_level` are still thrown, so the starting gold is the same as with the flag off. `examples/rulesets/creation_house_rules.json` is a ruleset with both house rules on and every other field at its default, for a front end to copy. With both flags at their defaults, every draw and result is what 2.8.0 gave. A 2.8.0 save loads with both off, a 2.8.0 creation result parses with an empty `dropped` and a false `maximized`, and [`SCHEMA_VERSION`][osrlib.versioning.SCHEMA_VERSION] stays 4. + ## [2.8.0] - 2026-11-25 ### Added diff --git a/src/osrlib/core/character.py b/src/osrlib/core/character.py index 5ce69fc..f5d4a6a 100644 --- a/src/osrlib/core/character.py +++ b/src/osrlib/core/character.py @@ -1108,13 +1108,21 @@ def roll_ability_scores(stream: RngStream, *, method: Literal["3d6", "4d6_drop_l # {'str': 14, 'int': 6, 'wis': 9, 'dex': 10, 'con': 11, 'cha': 11} ``` """ + if method not in ("3d6", "4d6_drop_lowest"): + raise ValueError(f"unknown ability score method {method!r}: use '3d6' or '4d6_drop_lowest'") scores: dict[AbilityScore, int] = {} rolls: dict[AbilityScore, tuple[int, int, int]] = {} + dropped: dict[AbilityScore, int] = {} for ability in ABILITY_ROLL_ORDER: - result = roll("3d6", stream) - scores[ability] = result.total - rolls[ability] = (result.rolls[0], result.rolls[1], result.rolls[2]) - return AbilityScoreRolls(scores=scores, rolls=rolls) + if method == "3d6": + thrown = list(roll("3d6", stream).rolls) + else: + thrown = list(roll("4d6", stream).rolls) + # `index` finds the first of the lowest dice thrown, so a tie drops the earliest one. + dropped[ability] = thrown.pop(thrown.index(min(thrown))) + scores[ability] = sum(thrown) + rolls[ability] = (thrown[0], thrown[1], thrown[2]) + return AbilityScoreRolls(scores=scores, rolls=rolls, dropped=dropped) def validate_class_choice(scores: dict[AbilityScore, int], definition: ClassDefinition) -> list[Rejection]: @@ -1228,7 +1236,14 @@ def roll_hit_points( if ruleset.hp_reroll_at_first_level: while rolls[-1] <= 2: rolls.append(stream.randbelow(die) + 1) - return HitPointRoll(rolls=tuple(rolls), hit_points=max(1, rolls[-1] + con_modifier)) + # The maximum replaces only the counted value, after every die has been thrown, so the draws are + # the same with the option on or off. + counted = die if ruleset.max_hp_at_first_level else rolls[-1] + return HitPointRoll( + rolls=tuple(rolls), + hit_points=max(1, counted + con_modifier), + maximized=ruleset.max_hp_at_first_level, + ) def validate_extra_languages(definition: ClassDefinition, int_score: int, choices: Sequence[str]) -> list[Rejection]: @@ -1642,7 +1657,7 @@ class can't equip. The message includes the choice that failed. A choice that do # `validate_purchase` refuses it. covered = sum(template.cost_gp * lots for template, lots in bought if lots > 0) _outfit(Inventory(purse=CoinPurse(gp=covered)), definition, bought, equip_ids) - ability_rolls = roll_ability_scores(stream) + ability_rolls = roll_ability_scores(stream, method=ruleset.ability_score_method) choice_rejections = validate_class_choice(ability_rolls.scores, definition) if choice_rejections: raise ValueError(f"illegal class choice: {[rejection.code for rejection in choice_rejections]}") From 91e3df4061d2cb075062d4d7a0177179fe34eb2d Mon Sep 17 00:00:00 2001 From: Marsh Macy Date: Thu, 26 Nov 2026 07:35:04 -0800 Subject: [PATCH 3/4] Document the character creation house rules in the spec and the adaptations register The adaptations register gains house rules as a third kind of entry and a House rules section with one entry for ability_score_method and one for max_hp_at_first_level, each citing the tests that lock it. The spec's Ruleset flag list and its rules-scope lines for ability scores and first-level hit points name the two flags, and the RNG streams page says the ability scores take 18 creation draws with 3d6 and 24 with 4d6 drop lowest (#341). Claude-Session: https://claude.ai/code/session_01V7Ertq3gKJ46oFQD6635f3 --- docs/adaptations.md | 32 +++++++++++++++++++++++++++++--- docs/reference/rng-streams.md | 2 +- docs/spec.md | 10 ++++++---- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/docs/adaptations.md b/docs/adaptations.md index 0493b60..241abe9 100644 --- a/docs/adaptations.md +++ b/docs/adaptations.md @@ -1,9 +1,10 @@ # Adaptations and interpretations -osrlib follows OSE rules-as-written (RAW). Every place where that isn't enough is recorded here, as one of two kinds of entry: +osrlib follows OSE rules-as-written (RAW). Every place where that isn't enough, and every house rule osrlib offers, is recorded here, as one of three kinds of entry: - **Interpretations**, where the SRD text is ambiguous or silent, and osrlib commits to one reading. - **Documented adaptations**, where the tabletop game assumes a human referee, and osrlib provides a default behind a `Ruleset` flag. +- **House rules**, which change a procedure in a way the SRD doesn't print. Each one is a `Ruleset` flag that's off by default, so `Ruleset()` is the SRD as written. Look here instead of searching docstrings. Every entry is also stated in the docstring of the member it applies to and locked by a test. @@ -19,7 +20,7 @@ Each entry also cites the source files and test names that lock it. Those citati - **Stable order** - When the engine sorts things that tie, it keeps them in the order it was given them, so the result never depends on chance. - **Kernel and session** - The kernel is `osrlib.core`, the rules functions you can call directly (see [Rules without a session](guides/rules-without-a-session.md)). The session is a [`GameSession`][osrlib.crawl.session.GameSession], which runs a whole adventure through commands and calls the kernel for you. - **Caller** - The code that calls a kernel function: your game, or the session. A value "the caller supplies" is an argument that code passes, because the kernel can't work it out. -- **Ruleset flags** - Options on [`Ruleset`][osrlib.core.ruleset.Ruleset]. Some switch the SRD's optional rules on or off, and others switch the defaults that [Documented adaptations](#documented-adaptations) lists. +- **Ruleset flags** - Options on [`Ruleset`][osrlib.core.ruleset.Ruleset]. Some switch the SRD's optional rules on or off, others switch the defaults that [Documented adaptations](#documented-adaptations) lists, and the rest turn on the rules that [House rules](#house-rules) lists. - **Marching order** - The order of the party's members. In battle, it decides who stands in front among members at the same distance from a group who got there in the same round. It also decides which member a rule means by "the first living member". - **Front rank and back rank** - In battle, the ranks toward a monster group are the living members sorted by their distance to it and cut into rows as wide as the formation width. The first row is the front rank toward that group, and every member behind it is in the back rank. Melee reaches only the members of the front rank who stand within 5' of the group. See [The battle round](#the-battle-round). - **Range track** - In battle, each monster group has a separate distance from the party line, where the party stood when the encounter opened, in the style of The Bard's Tale, instead of a position on a map. Each party member has a place on the same track, in feet forward of the line. @@ -1883,7 +1884,7 @@ Locked by `test_session.py` and the phase 5 milestone golden. ## Documented adaptations -`Ruleset`-flagged deviations from rules-as-written. The flags `hp_reroll_at_first_level`, `encumbrance`, `variable_weapon_damage`, `individual_initiative`, `thac0_arithmetic`, `weapon_reload`, and `hd5_counts_as_magical` are SRD optional rules rather than adaptations, so this section doesn't list them. +`Ruleset`-flagged deviations from rules-as-written. The flags `hp_reroll_at_first_level`, `encumbrance`, `variable_weapon_damage`, `individual_initiative`, `thac0_arithmetic`, `weapon_reload`, and `hd5_counts_as_magical` are SRD optional rules rather than adaptations, so this section doesn't list them. The flags `ability_score_method` and `max_hp_at_first_level` are house rules, which [House rules](#house-rules) lists. ### `deprivation_penalties` (default off) @@ -1933,3 +1934,28 @@ Items that survive go to the drop pile, a [`DropPile`][osrlib.crawl.dungeon.Drop - Dropping treasure never refunds its XP, so the return to town then awards nothing. Neither timing pays twice. Locked by `test_award.py::TestImmediateTiming`. + +## House rules + +These `Ruleset` flags turn on rules that the SRD doesn't print. Each one is off by default, so a game uses it only when you turn it on. `examples/rulesets/creation_house_rules.json` in the osrlib repository is a ruleset with both of these on. + +### `ability_score_method` (default `3d6`) + +`3d6` is RAW: each ability score is the sum of three d6. + +`4d6_drop_lowest` throws four d6 for each ability, and the lowest die doesn't count, so the score is the sum of the other three, from 3 to 18: + +- When two or more dice tie for lowest, the first of them thrown is dropped, so the same draws always give the same three dice in the same order. +- [`AbilityScoreRolls.rolls`][osrlib.core.character.AbilityScoreRolls.rolls] keeps the three dice that count, in the order thrown, and [`AbilityScoreRolls.dropped`][osrlib.core.character.AbilityScoreRolls.dropped] has the dropped die of each ability. +- All four dice of STR are thrown before any of INT, and so on in the SRD's order, so the scores take 24 draws from the creation stream instead of 18. The same seed gives different scores, and a different hit die and starting gold after them, than it gives with `3d6`. + +The method affects only the characters you create, and NPC adventurers always roll 3d6. Locked by `test_creation_house_rules.py::test_4d6_drop_lowest_counts_three_dice_and_names_the_dropped_one` and `test_creation_house_rules.py::test_4d6_drop_lowest_throws_the_draws_in_order_and_advances_24_dice`. + +### `max_hp_at_first_level` (default off) + +With the flag off, a first-level character's hit points are the class's hit die as rolled plus the CON modifier, as RAW says. With the flag on, they're the hit die's size plus the CON modifier, and at least 1, and [`HitPointRoll.maximized`][osrlib.core.character.HitPointRoll.maximized] is `True`: + +- The hit die is still thrown, and so are the rerolls of `hp_reroll_at_first_level`, so [`HitPointRoll.rolls`][osrlib.core.character.HitPointRoll.rolls] lists the same dice as with the flag off. The stream ends in the same place, so the starting gold roll after the hit die is the same either way. +- The flag affects only character creation. [`level_up`][osrlib.core.classes.level_up] rolls each later level's hit die as usual. + +Locked by `test_creation_house_rules.py::test_the_maximum_draws_what_the_roll_draws_so_the_gold_is_the_same` and `test_creation_house_rules.py::test_the_maximum_is_the_die_size_plus_the_modifier_and_at_least_1`. diff --git a/docs/reference/rng-streams.md b/docs/reference/rng-streams.md index defc846..9533518 100644 --- a/docs/reference/rng-streams.md +++ b/docs/reference/rng-streams.md @@ -28,7 +28,7 @@ The table below lists every key, the constant for it, and what it governs. Character creation and in-play advancement are split into two separate streams so that changing one never disturbs the other's draws. -The [`CHARACTER_CREATION_STREAM`][osrlib.core.character.CHARACTER_CREATION_STREAM] (key `"character_creation"`) covers one-time creation draws: rolling ability scores, first-level hit points, and starting gold. +The [`CHARACTER_CREATION_STREAM`][osrlib.core.character.CHARACTER_CREATION_STREAM] (key `"character_creation"`) covers one-time creation draws: rolling ability scores, first-level hit points, and starting gold. The ability scores take 18 d6 draws with the default `"3d6"` method and 24 with the `"4d6_drop_lowest"` house rule of `Ruleset.ability_score_method`, so the hit die and the gold that follow come from different draws under the two methods. The `max_hp_at_first_level` house rule changes no draw. The [`ADVANCEMENT_STREAM`][osrlib.core.character.ADVANCEMENT_STREAM] (key `"advancement"`) covers hit point rolls when a character levels up during play, and the hit point rolls for the levels or Hit Dice that energy drain takes away. diff --git a/docs/spec.md b/docs/spec.md index 057e444..da0f228 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -46,7 +46,7 @@ osrlib/ │ ├── rng.py # named PCG64 streams forked from a master seed │ ├── clock.py # time units (round, turn, day), game clock, tick scheduling │ ├── events.py # event base class + kernel event types -│ ├── ruleset.py # Ruleset model: optional-rule and adaptation flags +│ ├── ruleset.py # Ruleset model: optional-rule, adaptation, and house-rule flags │ ├── abilities.py # ability scores, modifiers, checks, prime requisite rules │ ├── classes.py # class definitions, level progression, XP, leveling & drain │ ├── character.py # PC model: scores, class, HP, inventory, spells, conditions @@ -282,8 +282,8 @@ Pipeline rules: The kernel implements B/X procedures rules-as-written: -- Ability scores 3d6, modifiers, prime requisite XP bonuses/penalties; the creation-time adjustment step (lower STR/INT/WIS two-for-one into a prime requisite, floor 9, class restrictions such as thieves keeping STR); ability checks (1d20, equal-or-under succeeds, ±4 easy/hard modifiers; natural 1 succeeds, natural 20 fails — inverted from attack rolls) and STR-based open-doors checks -- Character creation, starting gold and equipment, alignment, languages; optional re-roll of 1–2 starting hp as a `Ruleset` flag +- Ability scores 3d6, with 4d6 drop lowest as a `Ruleset` house rule, modifiers, prime requisite XP bonuses/penalties; the creation-time adjustment step (lower STR/INT/WIS two-for-one into a prime requisite, floor 9, class restrictions such as thieves keeping STR); ability checks (1d20, equal-or-under succeeds, ±4 easy/hard modifiers; natural 1 succeeds, natural 20 fails — inverted from attack rolls) and STR-based open-doors checks +- Character creation, starting gold and equipment, alignment, languages; optional re-roll of 1–2 starting hp as a `Ruleset` flag, and maximum first-level hp as a `Ruleset` house rule that throws the same dice - The attack matrix shipped as data (its clamping differs from plain THAC0 arithmetic, which becomes the `Ruleset` variant); natural 20 always hits, natural 1 always misses, minimum 1 damage on a hit; descending and ascending AC both supported - Combat round sequence: declaration, side initiative (individual as option), movement, missile, magic, melee; slow weapons act last; weapon qualities executed in resolution — two-handed (no shield), brace and charge doubling, optional reload, and splash weapons: burning oil (must be lit; creatures with fire attacks are immune) and holy water (harms only undead), dousing the target for two rounds as a timed effect; unarmed attacks (1d2) - Range bands with missile modifiers (+1 short, −1 long, impossible beyond long); melee only at 5' or less; fighting withdrawal (half speed) and retreat (attacker gains +2 and ignores the shield) @@ -324,7 +324,7 @@ Out of scope for 1.0 (tracked for later): wilderness and sea adventuring, strong ## The Ruleset -`core/ruleset.py` defines the `Ruleset` model: every SRD optional rule and every documented adaptation is a named flag with a default. The 1.0 flag set: +`core/ruleset.py` defines the `Ruleset` model: every SRD optional rule, every documented adaptation, and every house rule is a named flag with a default. A house rule is a change the SRD doesn't print, and its default is the SRD's procedure, so `Ruleset()` is the SRD as written. The 1.0 flag set, with the flags added since: - `variable_weapon_damage` (default on) — SRD optional rule; off means every weapon deals 1d6 - `individual_initiative` (default off) — DEX-modified individual initiative instead of side-based @@ -332,6 +332,8 @@ Out of scope for 1.0 (tracked for later): wilderness and sea adventuring, strong - `encumbrance` (default `basic`) — `none` / `basic` / `detailed` - `weapon_reload` (default off) — SRD optional rule: crossbows fire every other round - `hp_reroll_at_first_level` (default off) — re-roll starting hp results of 1–2 +- `max_hp_at_first_level` (default off), a house rule: a first-level character's hit die counts as its maximum. The dice are still thrown, so the starting gold roll after them doesn't change +- `ability_score_method` (default `3d6`), a house rule: `3d6` per the SRD, or `4d6_drop_lowest`, which throws four d6 per ability and drops the lowest. NPC adventurers always roll 3d6 - `hd5_counts_as_magical` (default off) — SRD optional rule: 5+ HD monsters bypass magic-only immunity - `magic_item_death_save` (default on) — the referee-optional save for magic items on destructive death - `deprivation_penalties` (default off) — adaptation: penalties for going without food/water From 69ff58d19083f7f06021376e8f232fe803eb7538 Mon Sep 17 00:00:00 2001 From: Marsh Macy Date: Thu, 26 Nov 2026 07:42:32 -0800 Subject: [PATCH 4/4] Remove the chunk markers and tidy three sentences after review The acceptance tests of the character creation house rules now run as ordinary tests. The review flagged an em dash and an en dash on two spec lines this branch rewrote, and an ambiguous sentence in the ruleset guide. Claude-Session: https://claude.ai/code/session_01V7Ertq3gKJ46oFQD6635f3 --- docs/guides/ruleset-options.md | 2 +- docs/spec.md | 4 ++-- tests/test_creation_house_rules.py | 13 ------------- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/docs/guides/ruleset-options.md b/docs/guides/ruleset-options.md index 496e6f1..9c73470 100644 --- a/docs/guides/ruleset-options.md +++ b/docs/guides/ruleset-options.md @@ -4,7 +4,7 @@ Configure optional B/X rules, referee adaptations, and house rules by constructi ## Construct a `Ruleset` -Call `Ruleset()` with no arguments for the default B/X configuration, the SRD as written with no house rule on, or override specific flags such as [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] to change how functions such as [`Character.movement_rate`][osrlib.core.character.Character.movement_rate] behave: +Call `Ruleset()` with no arguments for the default B/X configuration, which is the SRD as written with no house rule on. You can also override specific flags such as [`EncumbranceMode`][osrlib.core.ruleset.EncumbranceMode] to change how functions such as [`Character.movement_rate`][osrlib.core.character.Character.movement_rate] behave: ```python from pydantic import ValidationError diff --git a/docs/spec.md b/docs/spec.md index da0f228..c166f97 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -282,8 +282,8 @@ Pipeline rules: The kernel implements B/X procedures rules-as-written: -- Ability scores 3d6, with 4d6 drop lowest as a `Ruleset` house rule, modifiers, prime requisite XP bonuses/penalties; the creation-time adjustment step (lower STR/INT/WIS two-for-one into a prime requisite, floor 9, class restrictions such as thieves keeping STR); ability checks (1d20, equal-or-under succeeds, ±4 easy/hard modifiers; natural 1 succeeds, natural 20 fails — inverted from attack rolls) and STR-based open-doors checks -- Character creation, starting gold and equipment, alignment, languages; optional re-roll of 1–2 starting hp as a `Ruleset` flag, and maximum first-level hp as a `Ruleset` house rule that throws the same dice +- Ability scores 3d6, with 4d6 drop lowest as a `Ruleset` house rule, modifiers, prime requisite XP bonuses/penalties; the creation-time adjustment step (lower STR/INT/WIS two-for-one into a prime requisite, floor 9, class restrictions such as thieves keeping STR); ability checks (1d20, equal-or-under succeeds, ±4 easy/hard modifiers; natural 1 succeeds, natural 20 fails, inverted from attack rolls) and STR-based open-doors checks +- Character creation, starting gold and equipment, alignment, languages; optional re-roll of 1 or 2 starting hp as a `Ruleset` flag, and maximum first-level hp as a `Ruleset` house rule that throws the same dice - The attack matrix shipped as data (its clamping differs from plain THAC0 arithmetic, which becomes the `Ruleset` variant); natural 20 always hits, natural 1 always misses, minimum 1 damage on a hit; descending and ascending AC both supported - Combat round sequence: declaration, side initiative (individual as option), movement, missile, magic, melee; slow weapons act last; weapon qualities executed in resolution — two-handed (no shield), brace and charge doubling, optional reload, and splash weapons: burning oil (must be lit; creatures with fire attacks are immune) and holy water (harms only undead), dousing the target for two rounds as a timed effect; unarmed attacks (1d2) - Range bands with missile modifiers (+1 short, −1 long, impossible beyond long); melee only at 5' or less; fighting withdrawal (half speed) and retreat (attacker gains +2 and ignores the shield) diff --git a/tests/test_creation_house_rules.py b/tests/test_creation_house_rules.py index e5d5cc8..ec1e242 100644 --- a/tests/test_creation_house_rules.py +++ b/tests/test_creation_house_rules.py @@ -32,8 +32,6 @@ from osrlib.data import load_classes from osrlib.persistence import load_game -CHUNK = "chunk: creation-house-rules" - SAVES = Path(__file__).parent / "saves" SAVE_2_8_0 = SAVES / "creation_house_rules_save_2.8.0.json" """A save that osrlib 2.8.0 wrote, kept as written. @@ -259,7 +257,6 @@ def test_a_2_8_0_creation_result_parses_with_the_new_fields_at_their_defaults(): } -@pytest.mark.xfail(reason=CHUNK) @pytest.mark.parametrize("seed", sorted(FOUR_D6)) def test_4d6_drop_lowest_counts_three_dice_and_names_the_dropped_one(seed): expected = FOUR_D6[seed] @@ -274,7 +271,6 @@ def test_4d6_drop_lowest_counts_three_dice_and_names_the_dropped_one(seed): assert rolled.dropped[ability] <= min(rolled.rolls[ability]) -@pytest.mark.xfail(reason=CHUNK) @pytest.mark.parametrize("seed", sorted(FOUR_D6)) def test_4d6_drop_lowest_throws_the_draws_in_order_and_advances_24_dice(seed): creation = stream(seed) @@ -288,7 +284,6 @@ def test_4d6_drop_lowest_throws_the_draws_in_order_and_advances_24_dice(seed): assert creation.export_state() == replay.export_state() -@pytest.mark.xfail(reason=CHUNK) def test_4d6_drop_lowest_scores_range_from_3_to_18(): for seed in range(60): rolled = roll_ability_scores(stream(seed), method="4d6_drop_lowest") @@ -296,7 +291,6 @@ def test_4d6_drop_lowest_scores_range_from_3_to_18(): assert all(3 <= score <= 18 for score in rolled.scores.values()) -@pytest.mark.xfail(reason=CHUNK) def test_an_unknown_method_raises_before_the_first_draw(): creation = stream(7) before = creation.export_state() @@ -307,7 +301,6 @@ def test_an_unknown_method_raises_before_the_first_draw(): assert creation.export_state() == before -@pytest.mark.xfail(reason=CHUNK) def test_create_character_rolls_with_the_rulesets_method(): # Seed 2's 4d6 scores, from FOUR_D6, are STR 10, INT 14, WIS 15, DEX 13, CON 7, and CHA 14. After # the 24 ability dice, the fighter's d8 hit die is draw 25 and shows 6. CON 7 has a -1 hit @@ -340,7 +333,6 @@ def test_create_character_rolls_with_the_rulesets_method(): THIEF_GOLD = {False: ((5, 3, 2), 100), True: ((3, 2, 1), 60)} -@pytest.mark.xfail(reason=CHUNK) @pytest.mark.parametrize("reroll", [False, True]) def test_the_maximum_draws_what_the_roll_draws_so_the_gold_is_the_same(reroll): rolled, rolled_stream = create(7, "thief", Ruleset(hp_reroll_at_first_level=reroll)) @@ -360,7 +352,6 @@ def test_the_maximum_draws_what_the_roll_draws_so_the_gold_is_the_same(reroll): assert rolled.hit_point_roll.maximized is False -@pytest.mark.xfail(reason=CHUNK) def test_with_the_maximum_and_the_reroll_on_the_set_aside_dice_are_still_listed(): # The reroll still throws: the 2 is set aside and the 3 is the last die. The maximum replaces the # last die's value in the hit points only, so they're the d4's 4 plus a modifier of 0. @@ -376,7 +367,6 @@ def test_with_the_maximum_and_the_reroll_on_the_set_aside_dice_are_still_listed( HIT_DIE = {"cleric": 6, "dwarf": 8, "elf": 6, "fighter": 8, "halfling": 6, "magic_user": 4, "thief": 4} -@pytest.mark.xfail(reason=CHUNK) @pytest.mark.parametrize("class_id", sorted(HIT_DIE)) @pytest.mark.parametrize("con_modifier", [-5, -4, -3, -1, 0, 1, 3]) def test_the_maximum_is_the_die_size_plus_the_modifier_and_at_least_1(class_id, con_modifier): @@ -400,7 +390,6 @@ def test_the_maximum_is_the_die_size_plus_the_modifier_and_at_least_1(class_id, # ---------------------------------------------------------------------- both options together -@pytest.mark.xfail(reason=CHUNK) def test_both_options_in_one_create_character_call(): # The scores and the dice are seed 2's 4d6 drop lowest from FOUR_D6. CON 7 gives -1. The fighter's # d8 is draw 25, a 6, and the maximum counts it as 8, so the fighter has 8 - 1 = 7 hit points. The @@ -463,7 +452,6 @@ def test_the_example_readme_says_what_the_ruleset_changes_and_how_to_load_it(): assert "not the SRD" in readme -@pytest.mark.xfail(reason=CHUNK) def test_a_character_created_with_the_example_ruleset_has_4d6_scores_and_the_maximum(): # The same draws as test_both_options_in_one_create_character_call: seed 2's 4d6 drop lowest # scores, and the fighter's d8 at its maximum, 8, with CON 7's -1, for 7 hit points. @@ -480,7 +468,6 @@ def test_a_character_created_with_the_example_ruleset_has_4d6_scores_and_the_max # ---------------------------------------------------------------------- the changelog -@pytest.mark.xfail(reason=CHUNK) def test_the_changelog_bullet_names_both_options_and_both_fields(): bullets = [line for line in CHANGELOG.read_text(encoding="utf-8").splitlines() if "(#341)" in line] assert len(bullets) == 1