osrlib 2.5.0__tar.gz → 2.6.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- osrlib-2.6.0/PKG-INFO +197 -0
- osrlib-2.6.0/README.md +172 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/pyproject.toml +2 -2
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/__init__.py +10 -6
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/_descriptions.py +24 -4
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/dice.py +5 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/tables.py +38 -7
- osrlib-2.6.0/src/osrlib/crawl/_feature_handles.py +169 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_hauling.py +11 -9
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_movement.py +3 -4
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_party_location.py +14 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_search.py +16 -10
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_treasure.py +29 -4
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/adventure.py +62 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/battle.py +17 -9
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/commands.py +89 -51
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/dungeon.py +55 -21
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/session.py +42 -9
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/views.py +272 -20
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/persistence.py +33 -10
- osrlib-2.5.0/PKG-INFO +0 -147
- osrlib-2.5.0/README.md +0 -122
- {osrlib-2.5.0 → osrlib-2.6.0}/LICENSE +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/LICENSE-OGL.md +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/__init__.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/abilities.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/alignment.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/character.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/classes.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/clock.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/combat.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/creature.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/effects.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/events.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/frozen.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/items.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/monsters.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/npc.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/rng.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/ruleset.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/spells.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/treasure.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/core/validation.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/__init__.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_arrival.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_doors.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_gating.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_items.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_light.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_magic_items.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_odometer.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_party_members.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_spells.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/_town.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/content_pack.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/encounter.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/events.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/exploration.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/gates.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/interpreter.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/narrative.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/party.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/quests.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/stocking.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/crawl/triggers.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/LICENSE-OGL.md +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/__init__.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/abilities.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/classes.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/combat_tables.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/encounter_tables.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/equipment.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/languages.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/magic_items.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/monsters.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/spells.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/data/treasure.json +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/errors.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/messages.py +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/py.typed +0 -0
- {osrlib-2.5.0 → osrlib-2.6.0}/src/osrlib/versioning.py +0 -0
osrlib-2.6.0/PKG-INFO
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: osrlib
|
|
3
|
+
Version: 2.6.0
|
|
4
|
+
Summary: B/X (1981 Basic/Expert) tabletop RPG rules engine for turn-based dungeon crawlers
|
|
5
|
+
Keywords: basic-expert,bx,dungeon-crawler,game-engine,osr,rpg,srd,ttrpg
|
|
6
|
+
Author: Marsh Macy
|
|
7
|
+
License-Expression: MIT AND LicenseRef-OGL-1.0a
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: LICENSE-OGL.md
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Topic :: Games/Entertainment :: Role-Playing
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: pydantic>=2
|
|
19
|
+
Requires-Python: >=3.14
|
|
20
|
+
Project-URL: Changelog, https://github.com/mmacy/osrlib-python/blob/main/CHANGELOG.md
|
|
21
|
+
Project-URL: Documentation, https://mmacy.github.io/osrlib-python/
|
|
22
|
+
Project-URL: Issues, https://github.com/mmacy/osrlib-python/issues
|
|
23
|
+
Project-URL: Repository, https://github.com/mmacy/osrlib-python
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# osrlib
|
|
27
|
+
|
|
28
|
+
osrlib is a Python library that implements the classic 1981 B/X (Basic/Expert) fantasy adventure game rules for turn-based, grid-based dungeon crawlers in the style of the original Bard's Tale. The rules come from the [Old-School Essentials System Reference Document](https://oldschoolessentials.necroticgnome.com/srd/) (SRD), an Open Game Content restatement of the B/X rules.
|
|
29
|
+
|
|
30
|
+
osrlib has no UI, networking, or save-file I/O: you pass typed commands into an in-memory session, osrlib resolves the rules and updates game state, and your application handles rendering, player input, persistence, and transport. Every random roll draws from a named stream derived from a master seed, so running the same commands from the same starting state and seed under the same engine version produces the same game state and events every time.
|
|
31
|
+
|
|
32
|
+
osrlib separates standalone rules in `osrlib.core` (such as rolling characters, resolving attacks, or rolling treasure) from stateful dungeon-crawl sessions in `osrlib.crawl`, with shared top-level modules for compiled SRD data, message formatting, and persistence. In `osrlib.crawl`, you can bundle custom monsters, items, and spells with an adventure, put conditions on doors and stairs (which osrlib calls gates), and define quests and scripted reactions to play events (triggers).
|
|
33
|
+
|
|
34
|
+
You can use osrlib in several ways:
|
|
35
|
+
|
|
36
|
+
- **Web or mobile backends**: Serve game sessions over HTTP (for example, with FastAPI) using the generated Pydantic JSON Schemas for commands and events.
|
|
37
|
+
- **Terminal or desktop games**: Drive `GameSession` synchronously in process from a local interface.
|
|
38
|
+
- **LLM referees and narrators**: Pass structured events to a language model and execute the typed commands it returns.
|
|
39
|
+
- **Scripts and simulations**: Call functions in `osrlib.core` directly for character generation, combat statistics, or content validation without starting a session (see [Determinism, saves, and replay](#determinism-saves-and-replay) for a standalone dice roll and [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/)).
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
osrlib requires Python 3.14 or later, and its only runtime dependency is [pydantic](https://docs.pydantic.dev/). Public APIs follow semantic versioning.
|
|
44
|
+
|
|
45
|
+
In an existing [uv](https://docs.astral.sh/uv/) project (run `uv init` first in a new directory), install [osrlib from PyPI](https://pypi.org/project/osrlib/):
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
uv add osrlib
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or install into an active virtual environment with `pip`:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
python -m pip install osrlib
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quickstart
|
|
58
|
+
|
|
59
|
+
osrlib does not re-export names at the package root, so import each class or function from the module that defines it. Save the example below as `quickstart.py` to roll a party, move one cell east through a dungeon, print the movement message, and round-trip the session through JSON:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import json
|
|
63
|
+
|
|
64
|
+
from osrlib.core.alignment import Alignment
|
|
65
|
+
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
|
|
66
|
+
from osrlib.core.events import Visibility
|
|
67
|
+
from osrlib.core.rng import RngStreams
|
|
68
|
+
from osrlib.core.ruleset import Ruleset
|
|
69
|
+
from osrlib.crawl.adventure import Adventure, TownSpec
|
|
70
|
+
from osrlib.crawl.commands import EnterDungeon, MoveParty, SessionMode
|
|
71
|
+
from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
|
|
72
|
+
from osrlib.crawl.party import Party
|
|
73
|
+
from osrlib.crawl.session import GameSession
|
|
74
|
+
from osrlib.messages import format_message
|
|
75
|
+
from osrlib.persistence import load_game, save_game
|
|
76
|
+
|
|
77
|
+
# Roll two 1st-level characters; every random draw comes from a named, seeded stream.
|
|
78
|
+
rules = Ruleset()
|
|
79
|
+
creation = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
|
|
80
|
+
fighter = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
|
|
81
|
+
cleric = create_character(name="Osric", class_id="cleric", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
|
|
82
|
+
party = Party(members=[fighter.character, cleric.character])
|
|
83
|
+
|
|
84
|
+
# The smallest adventure: a town and a one-corridor dungeon, two cells joined west-east.
|
|
85
|
+
crypt = DungeonSpec(
|
|
86
|
+
id="crypt",
|
|
87
|
+
name="The Old Crypt",
|
|
88
|
+
levels=(LevelSpec(number=1, width=2, height=1, entrance=(0, 0), edges={"1,0:west": Edge(kind=EdgeKind.OPEN)}),),
|
|
89
|
+
)
|
|
90
|
+
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
|
|
91
|
+
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
|
|
92
|
+
|
|
93
|
+
# A session starts in town; entering the dungeon switches it to exploring.
|
|
94
|
+
session = GameSession.new(party, adventure, seed=7, ruleset=rules)
|
|
95
|
+
session.execute(EnterDungeon(dungeon_id="crypt"))
|
|
96
|
+
assert session.mode is SessionMode.EXPLORING
|
|
97
|
+
|
|
98
|
+
# Commands in, events out: filter to player-visible events before rendering.
|
|
99
|
+
result = session.execute(MoveParty(direction=Direction.EAST))
|
|
100
|
+
assert result.accepted
|
|
101
|
+
lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
|
|
102
|
+
print(lines[0])
|
|
103
|
+
# The party moves to (1, 0), facing east.
|
|
104
|
+
|
|
105
|
+
# The whole session round-trips through JSON.
|
|
106
|
+
document = save_game(session)
|
|
107
|
+
restored = load_game(json.loads(json.dumps(document)))
|
|
108
|
+
assert save_game(restored) == document
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Run `quickstart.py` with `uv`:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
uv run quickstart.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Or run it with the Python interpreter from your activated virtual environment:
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
python quickstart.py
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Running the script prints `The party moves to (1, 0), facing east.` and checks that the restored session serializes identically to the saved JSON. When adapting this snippet, keep these details in mind:
|
|
124
|
+
|
|
125
|
+
- **Map edges and travel**: Unlisted cell boundaries are walls. Setting `"1,0:west"` to `EdgeKind.OPEN` opens the west wall of `(1, 0)`, which is the shared boundary crossed when moving east from `entrance=(0, 0)`. `"crypt"` in `travel_turns={"crypt": 1}` matches `DungeonSpec(id="crypt", ...)` and `EnterDungeon(dungeon_id="crypt")`, advancing the clock by `1` ten-minute exploration turn on entry.
|
|
126
|
+
- **Session streams vs. creation streams**: `GameSession.new(..., seed=7)` creates a fresh set of session RNG streams from `seed`, separate from the `creation` stream used before play. If rolled ability scores miss a class's minimums, `create_character` advances `stream` and raises `ValueError`; retry with the same `stream` instance so the next attempt draws fresh rolls.
|
|
127
|
+
- **Player visibility and command rejections**: Filter `result.events` to `Visibility.PLAYER` before showing events to players so referee-only events stay hidden, and render screens from `session.view(Visibility.PLAYER)` rather than directly from `session` attributes. When a rule blocks a command (such as walking into a wall), `result.accepted` is `False`, `result.rejections` lists `Rejection` objects (each with a `code` and `params`), and session state, RNG streams, and the clock remain unchanged.
|
|
128
|
+
- **Capturing starting party state for replay**: `GameSession.new` assigns session-scoped IDs to `party.members`. If you plan to audit or replay the run from scratch with `replay_game` later, call `party_to_document(party.members)` (from `osrlib.core.character`) *before* calling `GameSession.new`.
|
|
129
|
+
|
|
130
|
+
For a step-by-step walkthrough of this program, see the [Quickstart guide](https://mmacy.github.io/osrlib-python/getting-started/quickstart/).
|
|
131
|
+
|
|
132
|
+
## Determinism, saves, and replay
|
|
133
|
+
|
|
134
|
+
osrlib never calls Python's `random` module. Every random draw comes from a named PCG64 stream (`RngStream`) managed by `RngStreams`. Calling `streams.get("treasure")` repeatedly on the same `RngStreams` instance returns the same stateful stream, advancing on each roll without shifting other streams such as `"combat"`. Creating a new `RngStreams` with the same `master_seed` reproduces the sequence from the first draw:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from osrlib.core.dice import roll
|
|
138
|
+
from osrlib.core.rng import RngStreams
|
|
139
|
+
|
|
140
|
+
treasure_a = RngStreams(master_seed=42).get("treasure")
|
|
141
|
+
rolls_a = [roll("2d6×10", treasure_a).total for _ in range(3)]
|
|
142
|
+
print(rolls_a)
|
|
143
|
+
# [60, 80, 100]
|
|
144
|
+
|
|
145
|
+
treasure_b = RngStreams(master_seed=42).get("treasure")
|
|
146
|
+
rolls_b = [roll("2d6×10", treasure_b).total for _ in range(3)]
|
|
147
|
+
assert rolls_a == rolls_b
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Choose how you persist a session based on whether you need to continue play or audit a run:
|
|
151
|
+
|
|
152
|
+
- **To continue playing later, save the session (`save_game` / `load_game`)**: `save_game` serializes a running session (including the embedded adventure, current party, explored dungeon state, RNG stream positions, `command_log`, and `event_log`) to a JSON-compatible dict stamped with `schema_version` and `engine_version`. `load_game` restores that state directly without re-running commands and automatically upgrades saves written under older schema versions. Because saves store JSON data rather than Python objects, re-register any event listeners and custom monster AI policies (`action_policies`) on the restored session before executing new commands.
|
|
153
|
+
- **To audit or reproduce a run from scratch, also save the starting inputs (`replay_game`)**: Under the same `engine_version`, `replay_game` starts a fresh session from the master seed, a pre-session party document (captured with `party_to_document` before `GameSession.new` assigns member IDs), the adventure, and the `Ruleset`, then re-executes `command_log`. It reproduces all command-driven state, including commands that listeners issued during original play, but omits private `listener_state` dicts and events that listeners returned directly without executing a command.
|
|
154
|
+
|
|
155
|
+
## Documentation
|
|
156
|
+
|
|
157
|
+
Read the [documentation site](https://mmacy.github.io/osrlib-python/) for guides, walkthroughs, and full reference pages for every public symbol, command, event, rejection code, message code, RNG stream, and content ID:
|
|
158
|
+
|
|
159
|
+
- **Build a dungeon**: [Building an adventure](https://mmacy.github.io/osrlib-python/getting-started/building-an-adventure/) covers laying out a dungeon grid with doors and a keyed encounter, adding features, traps, treasure, and transitions, and validating the adventure.
|
|
160
|
+
- **Run the command and event loop**: [Sessions, commands, and events](https://mmacy.github.io/osrlib-python/guides/sessions-commands-events/) covers session modes, command rejections, JSON serialization, and the event log.
|
|
161
|
+
- **Add conditional doors, scripted events, and quests**: [Gates, triggers, and quests](https://mmacy.github.io/osrlib-python/guides/gates-triggers-quests/) covers gating doors and transitions, scripting triggers, defining quests, and registering the built-in `Interpreter` listener to advance quests to a `victory` ending.
|
|
162
|
+
- **Call rules without a session**: [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/) covers calling `osrlib.core` functions directly for combat, character creation, spells, and treasure.
|
|
163
|
+
- **Connect a UI, HTTP server, or LLM**: [The TUI crawler](https://mmacy.github.io/osrlib-python/front-ends/tui-crawler/) and [The FastAPI pattern](https://mmacy.github.io/osrlib-python/front-ends/fastapi-pattern/) walk through the terminal and HTTP applications in `examples/`, and [LLM referees](https://mmacy.github.io/osrlib-python/front-ends/llm-referees/) shows how to connect an LLM agent to commands and events.
|
|
164
|
+
- **Configure B/X rule options and adaptations**: [Ruleset options](https://mmacy.github.io/osrlib-python/guides/ruleset-options/) lists configurable rule flags on `Ruleset`, and the [Adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) documents how osrlib resolves ambiguous B/X rules and tabletop referee procedures.
|
|
165
|
+
|
|
166
|
+
## Contributing
|
|
167
|
+
|
|
168
|
+
Development requires Python 3.14 or later and [uv](https://docs.astral.sh/uv/). Clone the repository, install the development, documentation, and example dependencies with `uv sync`, and run the CI checks:
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
git clone https://github.com/mmacy/osrlib-python.git
|
|
172
|
+
cd osrlib-python
|
|
173
|
+
uv sync
|
|
174
|
+
uv run ruff format --check
|
|
175
|
+
uv run ruff check
|
|
176
|
+
uv run pyright
|
|
177
|
+
uv run pytest
|
|
178
|
+
uv run mkdocs build --strict
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
See [the specification](https://github.com/mmacy/osrlib-python/blob/main/docs/spec.md) for the architecture, contracts, and rules scope.
|
|
182
|
+
|
|
183
|
+
### SRD data pipeline
|
|
184
|
+
|
|
185
|
+
The compiler in `tools/srd_compile/` parses the scraped SRD markdown in `srd/` and writes the validated JSON data files in `src/osrlib/data/`. Do not edit `srd/` or `src/osrlib/data/` by hand. After changing compiler code or overrides, regenerate the data files and commit the updated files in `src/osrlib/data/` with your change:
|
|
186
|
+
|
|
187
|
+
```sh
|
|
188
|
+
uv run python -m tools.srd_compile
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
CI runs this command and fails if `src/osrlib/data/` has uncommitted changes. Put parser corrections in `tools/srd_compile/overrides/` with a non-empty `reason` field; the compiler applies them during generation and records each modified field path in the entry's `overrides_applied` list.
|
|
192
|
+
|
|
193
|
+
## Licensing
|
|
194
|
+
|
|
195
|
+
Library code is licensed under the [MIT license](https://github.com/mmacy/osrlib-python/blob/main/LICENSE). SRD-derived content (the scraped SRD markdown in `srd/` and the compiled game data in `src/osrlib/data/`) is Open Game Content under the [Open Game License 1.0a](https://github.com/mmacy/osrlib-python/blob/main/LICENSE-OGL.md), which includes the complete Section 15 copyright notice. Built wheels include a copy of `LICENSE-OGL.md` with the osrlib Section 15 entry inside `osrlib/data/`.
|
|
196
|
+
|
|
197
|
+
osrlib is an independent project and is not affiliated with or endorsed by Necrotic Gnome. "Old-School Essentials" is a trademark of Necrotic Gnome, used here only to identify the source document. osrlib makes no claim of compatibility.
|
osrlib-2.6.0/README.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# osrlib
|
|
2
|
+
|
|
3
|
+
osrlib is a Python library that implements the classic 1981 B/X (Basic/Expert) fantasy adventure game rules for turn-based, grid-based dungeon crawlers in the style of the original Bard's Tale. The rules come from the [Old-School Essentials System Reference Document](https://oldschoolessentials.necroticgnome.com/srd/) (SRD), an Open Game Content restatement of the B/X rules.
|
|
4
|
+
|
|
5
|
+
osrlib has no UI, networking, or save-file I/O: you pass typed commands into an in-memory session, osrlib resolves the rules and updates game state, and your application handles rendering, player input, persistence, and transport. Every random roll draws from a named stream derived from a master seed, so running the same commands from the same starting state and seed under the same engine version produces the same game state and events every time.
|
|
6
|
+
|
|
7
|
+
osrlib separates standalone rules in `osrlib.core` (such as rolling characters, resolving attacks, or rolling treasure) from stateful dungeon-crawl sessions in `osrlib.crawl`, with shared top-level modules for compiled SRD data, message formatting, and persistence. In `osrlib.crawl`, you can bundle custom monsters, items, and spells with an adventure, put conditions on doors and stairs (which osrlib calls gates), and define quests and scripted reactions to play events (triggers).
|
|
8
|
+
|
|
9
|
+
You can use osrlib in several ways:
|
|
10
|
+
|
|
11
|
+
- **Web or mobile backends**: Serve game sessions over HTTP (for example, with FastAPI) using the generated Pydantic JSON Schemas for commands and events.
|
|
12
|
+
- **Terminal or desktop games**: Drive `GameSession` synchronously in process from a local interface.
|
|
13
|
+
- **LLM referees and narrators**: Pass structured events to a language model and execute the typed commands it returns.
|
|
14
|
+
- **Scripts and simulations**: Call functions in `osrlib.core` directly for character generation, combat statistics, or content validation without starting a session (see [Determinism, saves, and replay](#determinism-saves-and-replay) for a standalone dice roll and [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/)).
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
osrlib requires Python 3.14 or later, and its only runtime dependency is [pydantic](https://docs.pydantic.dev/). Public APIs follow semantic versioning.
|
|
19
|
+
|
|
20
|
+
In an existing [uv](https://docs.astral.sh/uv/) project (run `uv init` first in a new directory), install [osrlib from PyPI](https://pypi.org/project/osrlib/):
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
uv add osrlib
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Or install into an active virtual environment with `pip`:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
python -m pip install osrlib
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quickstart
|
|
33
|
+
|
|
34
|
+
osrlib does not re-export names at the package root, so import each class or function from the module that defines it. Save the example below as `quickstart.py` to roll a party, move one cell east through a dungeon, print the movement message, and round-trip the session through JSON:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import json
|
|
38
|
+
|
|
39
|
+
from osrlib.core.alignment import Alignment
|
|
40
|
+
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
|
|
41
|
+
from osrlib.core.events import Visibility
|
|
42
|
+
from osrlib.core.rng import RngStreams
|
|
43
|
+
from osrlib.core.ruleset import Ruleset
|
|
44
|
+
from osrlib.crawl.adventure import Adventure, TownSpec
|
|
45
|
+
from osrlib.crawl.commands import EnterDungeon, MoveParty, SessionMode
|
|
46
|
+
from osrlib.crawl.dungeon import Direction, DungeonSpec, Edge, EdgeKind, LevelSpec
|
|
47
|
+
from osrlib.crawl.party import Party
|
|
48
|
+
from osrlib.crawl.session import GameSession
|
|
49
|
+
from osrlib.messages import format_message
|
|
50
|
+
from osrlib.persistence import load_game, save_game
|
|
51
|
+
|
|
52
|
+
# Roll two 1st-level characters; every random draw comes from a named, seeded stream.
|
|
53
|
+
rules = Ruleset()
|
|
54
|
+
creation = RngStreams(master_seed=7).get(CHARACTER_CREATION_STREAM)
|
|
55
|
+
fighter = create_character(name="Hild", class_id="fighter", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
|
|
56
|
+
cleric = create_character(name="Osric", class_id="cleric", alignment=Alignment.LAWFUL, ruleset=rules, stream=creation)
|
|
57
|
+
party = Party(members=[fighter.character, cleric.character])
|
|
58
|
+
|
|
59
|
+
# The smallest adventure: a town and a one-corridor dungeon, two cells joined west-east.
|
|
60
|
+
crypt = DungeonSpec(
|
|
61
|
+
id="crypt",
|
|
62
|
+
name="The Old Crypt",
|
|
63
|
+
levels=(LevelSpec(number=1, width=2, height=1, entrance=(0, 0), edges={"1,0:west": Edge(kind=EdgeKind.OPEN)}),),
|
|
64
|
+
)
|
|
65
|
+
town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
|
|
66
|
+
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
|
|
67
|
+
|
|
68
|
+
# A session starts in town; entering the dungeon switches it to exploring.
|
|
69
|
+
session = GameSession.new(party, adventure, seed=7, ruleset=rules)
|
|
70
|
+
session.execute(EnterDungeon(dungeon_id="crypt"))
|
|
71
|
+
assert session.mode is SessionMode.EXPLORING
|
|
72
|
+
|
|
73
|
+
# Commands in, events out: filter to player-visible events before rendering.
|
|
74
|
+
result = session.execute(MoveParty(direction=Direction.EAST))
|
|
75
|
+
assert result.accepted
|
|
76
|
+
lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
|
|
77
|
+
print(lines[0])
|
|
78
|
+
# The party moves to (1, 0), facing east.
|
|
79
|
+
|
|
80
|
+
# The whole session round-trips through JSON.
|
|
81
|
+
document = save_game(session)
|
|
82
|
+
restored = load_game(json.loads(json.dumps(document)))
|
|
83
|
+
assert save_game(restored) == document
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Run `quickstart.py` with `uv`:
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
uv run quickstart.py
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Or run it with the Python interpreter from your activated virtual environment:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
python quickstart.py
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Running the script prints `The party moves to (1, 0), facing east.` and checks that the restored session serializes identically to the saved JSON. When adapting this snippet, keep these details in mind:
|
|
99
|
+
|
|
100
|
+
- **Map edges and travel**: Unlisted cell boundaries are walls. Setting `"1,0:west"` to `EdgeKind.OPEN` opens the west wall of `(1, 0)`, which is the shared boundary crossed when moving east from `entrance=(0, 0)`. `"crypt"` in `travel_turns={"crypt": 1}` matches `DungeonSpec(id="crypt", ...)` and `EnterDungeon(dungeon_id="crypt")`, advancing the clock by `1` ten-minute exploration turn on entry.
|
|
101
|
+
- **Session streams vs. creation streams**: `GameSession.new(..., seed=7)` creates a fresh set of session RNG streams from `seed`, separate from the `creation` stream used before play. If rolled ability scores miss a class's minimums, `create_character` advances `stream` and raises `ValueError`; retry with the same `stream` instance so the next attempt draws fresh rolls.
|
|
102
|
+
- **Player visibility and command rejections**: Filter `result.events` to `Visibility.PLAYER` before showing events to players so referee-only events stay hidden, and render screens from `session.view(Visibility.PLAYER)` rather than directly from `session` attributes. When a rule blocks a command (such as walking into a wall), `result.accepted` is `False`, `result.rejections` lists `Rejection` objects (each with a `code` and `params`), and session state, RNG streams, and the clock remain unchanged.
|
|
103
|
+
- **Capturing starting party state for replay**: `GameSession.new` assigns session-scoped IDs to `party.members`. If you plan to audit or replay the run from scratch with `replay_game` later, call `party_to_document(party.members)` (from `osrlib.core.character`) *before* calling `GameSession.new`.
|
|
104
|
+
|
|
105
|
+
For a step-by-step walkthrough of this program, see the [Quickstart guide](https://mmacy.github.io/osrlib-python/getting-started/quickstart/).
|
|
106
|
+
|
|
107
|
+
## Determinism, saves, and replay
|
|
108
|
+
|
|
109
|
+
osrlib never calls Python's `random` module. Every random draw comes from a named PCG64 stream (`RngStream`) managed by `RngStreams`. Calling `streams.get("treasure")` repeatedly on the same `RngStreams` instance returns the same stateful stream, advancing on each roll without shifting other streams such as `"combat"`. Creating a new `RngStreams` with the same `master_seed` reproduces the sequence from the first draw:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from osrlib.core.dice import roll
|
|
113
|
+
from osrlib.core.rng import RngStreams
|
|
114
|
+
|
|
115
|
+
treasure_a = RngStreams(master_seed=42).get("treasure")
|
|
116
|
+
rolls_a = [roll("2d6×10", treasure_a).total for _ in range(3)]
|
|
117
|
+
print(rolls_a)
|
|
118
|
+
# [60, 80, 100]
|
|
119
|
+
|
|
120
|
+
treasure_b = RngStreams(master_seed=42).get("treasure")
|
|
121
|
+
rolls_b = [roll("2d6×10", treasure_b).total for _ in range(3)]
|
|
122
|
+
assert rolls_a == rolls_b
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Choose how you persist a session based on whether you need to continue play or audit a run:
|
|
126
|
+
|
|
127
|
+
- **To continue playing later, save the session (`save_game` / `load_game`)**: `save_game` serializes a running session (including the embedded adventure, current party, explored dungeon state, RNG stream positions, `command_log`, and `event_log`) to a JSON-compatible dict stamped with `schema_version` and `engine_version`. `load_game` restores that state directly without re-running commands and automatically upgrades saves written under older schema versions. Because saves store JSON data rather than Python objects, re-register any event listeners and custom monster AI policies (`action_policies`) on the restored session before executing new commands.
|
|
128
|
+
- **To audit or reproduce a run from scratch, also save the starting inputs (`replay_game`)**: Under the same `engine_version`, `replay_game` starts a fresh session from the master seed, a pre-session party document (captured with `party_to_document` before `GameSession.new` assigns member IDs), the adventure, and the `Ruleset`, then re-executes `command_log`. It reproduces all command-driven state, including commands that listeners issued during original play, but omits private `listener_state` dicts and events that listeners returned directly without executing a command.
|
|
129
|
+
|
|
130
|
+
## Documentation
|
|
131
|
+
|
|
132
|
+
Read the [documentation site](https://mmacy.github.io/osrlib-python/) for guides, walkthroughs, and full reference pages for every public symbol, command, event, rejection code, message code, RNG stream, and content ID:
|
|
133
|
+
|
|
134
|
+
- **Build a dungeon**: [Building an adventure](https://mmacy.github.io/osrlib-python/getting-started/building-an-adventure/) covers laying out a dungeon grid with doors and a keyed encounter, adding features, traps, treasure, and transitions, and validating the adventure.
|
|
135
|
+
- **Run the command and event loop**: [Sessions, commands, and events](https://mmacy.github.io/osrlib-python/guides/sessions-commands-events/) covers session modes, command rejections, JSON serialization, and the event log.
|
|
136
|
+
- **Add conditional doors, scripted events, and quests**: [Gates, triggers, and quests](https://mmacy.github.io/osrlib-python/guides/gates-triggers-quests/) covers gating doors and transitions, scripting triggers, defining quests, and registering the built-in `Interpreter` listener to advance quests to a `victory` ending.
|
|
137
|
+
- **Call rules without a session**: [Using the rules without a session](https://mmacy.github.io/osrlib-python/guides/rules-without-a-session/) covers calling `osrlib.core` functions directly for combat, character creation, spells, and treasure.
|
|
138
|
+
- **Connect a UI, HTTP server, or LLM**: [The TUI crawler](https://mmacy.github.io/osrlib-python/front-ends/tui-crawler/) and [The FastAPI pattern](https://mmacy.github.io/osrlib-python/front-ends/fastapi-pattern/) walk through the terminal and HTTP applications in `examples/`, and [LLM referees](https://mmacy.github.io/osrlib-python/front-ends/llm-referees/) shows how to connect an LLM agent to commands and events.
|
|
139
|
+
- **Configure B/X rule options and adaptations**: [Ruleset options](https://mmacy.github.io/osrlib-python/guides/ruleset-options/) lists configurable rule flags on `Ruleset`, and the [Adaptations register](https://mmacy.github.io/osrlib-python/adaptations/) documents how osrlib resolves ambiguous B/X rules and tabletop referee procedures.
|
|
140
|
+
|
|
141
|
+
## Contributing
|
|
142
|
+
|
|
143
|
+
Development requires Python 3.14 or later and [uv](https://docs.astral.sh/uv/). Clone the repository, install the development, documentation, and example dependencies with `uv sync`, and run the CI checks:
|
|
144
|
+
|
|
145
|
+
```sh
|
|
146
|
+
git clone https://github.com/mmacy/osrlib-python.git
|
|
147
|
+
cd osrlib-python
|
|
148
|
+
uv sync
|
|
149
|
+
uv run ruff format --check
|
|
150
|
+
uv run ruff check
|
|
151
|
+
uv run pyright
|
|
152
|
+
uv run pytest
|
|
153
|
+
uv run mkdocs build --strict
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
See [the specification](https://github.com/mmacy/osrlib-python/blob/main/docs/spec.md) for the architecture, contracts, and rules scope.
|
|
157
|
+
|
|
158
|
+
### SRD data pipeline
|
|
159
|
+
|
|
160
|
+
The compiler in `tools/srd_compile/` parses the scraped SRD markdown in `srd/` and writes the validated JSON data files in `src/osrlib/data/`. Do not edit `srd/` or `src/osrlib/data/` by hand. After changing compiler code or overrides, regenerate the data files and commit the updated files in `src/osrlib/data/` with your change:
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
uv run python -m tools.srd_compile
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
CI runs this command and fails if `src/osrlib/data/` has uncommitted changes. Put parser corrections in `tools/srd_compile/overrides/` with a non-empty `reason` field; the compiler applies them during generation and records each modified field path in the entry's `overrides_applied` list.
|
|
167
|
+
|
|
168
|
+
## Licensing
|
|
169
|
+
|
|
170
|
+
Library code is licensed under the [MIT license](https://github.com/mmacy/osrlib-python/blob/main/LICENSE). SRD-derived content (the scraped SRD markdown in `srd/` and the compiled game data in `src/osrlib/data/`) is Open Game Content under the [Open Game License 1.0a](https://github.com/mmacy/osrlib-python/blob/main/LICENSE-OGL.md), which includes the complete Section 15 copyright notice. Built wheels include a copy of `LICENSE-OGL.md` with the osrlib Section 15 entry inside `osrlib/data/`.
|
|
171
|
+
|
|
172
|
+
osrlib is an independent project and is not affiliated with or endorsed by Necrotic Gnome. "Old-School Essentials" is a trademark of Necrotic Gnome, used here only to identify the source document. osrlib makes no claim of compatibility.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "osrlib"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.6.0"
|
|
4
4
|
description = "B/X (1981 Basic/Expert) tabletop RPG rules engine for turn-based dungeon crawlers"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
# The wheel ships Open Game Content (osrlib/data/*.json and its LICENSE-OGL.md
|
|
@@ -71,7 +71,7 @@ docs = [
|
|
|
71
71
|
# the package's runtime dependency remains pydantic alone.
|
|
72
72
|
examples = [
|
|
73
73
|
"fastapi>=0.115",
|
|
74
|
-
"
|
|
74
|
+
"httpx2>=2.16.2",
|
|
75
75
|
"uvicorn>=0.32",
|
|
76
76
|
]
|
|
77
77
|
|
|
@@ -89,8 +89,11 @@ events, save, and load. For a step-by-step explanation of this example, see the
|
|
|
89
89
|
https://mmacy.github.io/osrlib-python/getting-started/quickstart/.
|
|
90
90
|
|
|
91
91
|
```python
|
|
92
|
+
import json
|
|
93
|
+
|
|
92
94
|
from osrlib.core.alignment import Alignment
|
|
93
95
|
from osrlib.core.character import CHARACTER_CREATION_STREAM, create_character
|
|
96
|
+
from osrlib.core.events import Visibility
|
|
94
97
|
from osrlib.core.rng import RngStreams
|
|
95
98
|
from osrlib.core.ruleset import Ruleset
|
|
96
99
|
from osrlib.crawl.adventure import Adventure, TownSpec
|
|
@@ -118,19 +121,20 @@ town = TownSpec(name="Threshold", travel_turns={"crypt": 1})
|
|
|
118
121
|
adventure = Adventure(name="A First Delve", town=town, dungeons=(crypt,))
|
|
119
122
|
|
|
120
123
|
# A session starts in town; entering the dungeon switches it to exploring.
|
|
121
|
-
session = GameSession.new(party, adventure, seed=7)
|
|
124
|
+
session = GameSession.new(party, adventure, seed=7, ruleset=rules)
|
|
122
125
|
session.execute(EnterDungeon(dungeon_id="crypt"))
|
|
123
126
|
assert session.mode is SessionMode.EXPLORING
|
|
124
127
|
|
|
125
|
-
# Commands in, events out:
|
|
128
|
+
# Commands in, events out: filter to player-visible events before rendering.
|
|
126
129
|
result = session.execute(MoveParty(direction=Direction.EAST))
|
|
127
130
|
assert result.accepted
|
|
128
|
-
lines = [format_message(event) for event in result.events]
|
|
129
|
-
|
|
131
|
+
lines = [format_message(event) for event in result.events if event.visibility is Visibility.PLAYER]
|
|
132
|
+
print(lines[0])
|
|
133
|
+
# The party moves to (1, 0), facing east.
|
|
130
134
|
|
|
131
|
-
# The whole session round-trips through JSON
|
|
135
|
+
# The whole session round-trips through JSON.
|
|
132
136
|
document = save_game(session)
|
|
133
|
-
restored = load_game(document)
|
|
137
|
+
restored = load_game(json.loads(json.dumps(document)))
|
|
134
138
|
assert save_game(restored) == document
|
|
135
139
|
```
|
|
136
140
|
"""
|
|
@@ -13,8 +13,10 @@ enum's schema.
|
|
|
13
13
|
|
|
14
14
|
A description reaches its reader as raw text, outside the documentation site, so `_describe` and `_StrEnum` reduce each
|
|
15
15
|
mkdocstrings cross-reference, like ``[`MoveParty`][osrlib.crawl.commands.MoveParty]``, to its label, `` `MoveParty` ``.
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
A label that is code and a code span that touches it become one code span, so
|
|
17
|
+
``[`load_classes`][osrlib.data.load_classes]`().get(class_id)` `` becomes `` `load_classes().get(class_id)` ``, the
|
|
18
|
+
run of code that the documentation site shows. Markdown doesn't treat anything inside code as a link, so brackets in
|
|
19
|
+
code, like `inventory["purse"]["gp"]`, stay as they are.
|
|
18
20
|
"""
|
|
19
21
|
|
|
20
22
|
import ast
|
|
@@ -41,15 +43,33 @@ _LITERAL = re.compile(r"(```.*?```|~~~.*?~~~|``.+?``)", re.DOTALL)
|
|
|
41
43
|
_SPAN_OR_REFERENCE = re.compile(r"(`[^`\n]+`)|\[((?:[^\[\]`]|`[^`\n]+`)+)\]\[[^\]\s]+\]")
|
|
42
44
|
|
|
43
45
|
|
|
46
|
+
# Marks each end of a reduced label while `_plain` works: a NUL character, which Markdown prose doesn't contain.
|
|
47
|
+
_EDGE = "\x00"
|
|
48
|
+
|
|
49
|
+
# The end of one code span and the start of the next, with only the ends of reduced labels between them.
|
|
50
|
+
_JOIN = re.compile(f"`{_EDGE}+`")
|
|
51
|
+
|
|
52
|
+
|
|
44
53
|
def _plain(text: str) -> str:
|
|
45
|
-
"""Return Markdown with each mkdocstrings cross-reference reduced to its label, and code left as it is.
|
|
54
|
+
"""Return Markdown with each mkdocstrings cross-reference reduced to its label, and code left as it is.
|
|
55
|
+
|
|
56
|
+
A label that is code can touch a code span, like ``[`load_classes`][osrlib.data.load_classes]`()` ``, which the
|
|
57
|
+
documentation site shows as one run of code with a link on its first part. `_plain` joins the two into one code
|
|
58
|
+
span, `` `load_classes()` ``. With a space between them, like ``[`load_spells`][osrlib.data.load_spells] `()` ``,
|
|
59
|
+
they stay two spans.
|
|
60
|
+
"""
|
|
46
61
|
if "][" not in text:
|
|
47
62
|
return text
|
|
48
63
|
parts = _LITERAL.split(text)
|
|
49
|
-
parts[::2] = [
|
|
64
|
+
parts[::2] = [_JOIN.sub("", _SPAN_OR_REFERENCE.sub(_mark_label, part)).replace(_EDGE, "") for part in parts[::2]]
|
|
50
65
|
return "".join(parts)
|
|
51
66
|
|
|
52
67
|
|
|
68
|
+
def _mark_label(match: re.Match[str]) -> str:
|
|
69
|
+
"""Return a code span as it is, or a cross-reference's label with each end marked."""
|
|
70
|
+
return match.group(1) or f"{_EDGE}{match.group(2)}{_EDGE}"
|
|
71
|
+
|
|
72
|
+
|
|
53
73
|
@cache
|
|
54
74
|
def _module_docstrings(module_name: str) -> dict[str, dict[str, str]]:
|
|
55
75
|
"""Map the qualified name of each class in a module to the plain docstrings of the fields it declares.
|
|
@@ -244,6 +244,11 @@ def _lowest_total(expression: DiceExpression) -> int:
|
|
|
244
244
|
return (expression.count + expression.modifier) * expression.multiplier
|
|
245
245
|
|
|
246
246
|
|
|
247
|
+
def _highest_total(expression: DiceExpression) -> int:
|
|
248
|
+
"""Return the highest total `expression` can roll, with every die showing its highest face."""
|
|
249
|
+
return (expression.count * expression.sides + expression.modifier) * expression.multiplier
|
|
250
|
+
|
|
251
|
+
|
|
247
252
|
def roll(expression: str | DiceExpression, stream: RngStream) -> RollResult:
|
|
248
253
|
"""Roll a dice expression, drawing from the stream you pass.
|
|
249
254
|
|
|
@@ -59,7 +59,7 @@ from pydantic import ConfigDict, Field, field_validator, model_validator
|
|
|
59
59
|
|
|
60
60
|
from osrlib.core._descriptions import _StrEnum
|
|
61
61
|
from osrlib.core.classes import SavingThrows
|
|
62
|
-
from osrlib.core.dice import _lowest_total, parse, roll
|
|
62
|
+
from osrlib.core.dice import _highest_total, _lowest_total, parse, roll
|
|
63
63
|
from osrlib.core.frozen import FrozenMap, _Model
|
|
64
64
|
from osrlib.core.monsters import MonsterHitDice
|
|
65
65
|
from osrlib.core.rng import RngStream
|
|
@@ -594,6 +594,29 @@ assert isinstance(entry, MonsterEncounterEntry)
|
|
|
594
594
|
"""
|
|
595
595
|
|
|
596
596
|
|
|
597
|
+
_SPAWN_LIMIT = 100
|
|
598
|
+
"""The most monsters or adventurers one count creates: a spawn command's count, a keyed
|
|
599
|
+
encounter's lines together, or a wandering monster table row's count. 100 is the largest number
|
|
600
|
+
in the B/X monster data, for normal bats and for wild horses in a lair. It lives here because
|
|
601
|
+
`osrlib.core` can't import `osrlib.crawl`, and the crawl models and commands that share it import
|
|
602
|
+
it from here. The `count_fixed` fields state it as a literal `le=100`, because the reference
|
|
603
|
+
pages render a field's value and must not show a private name."""
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _spawn_count_dice(expression: str) -> str:
|
|
607
|
+
"""Return a `count_dice` expression, or raise `ValueError` when it can roll past `_SPAWN_LIMIT`.
|
|
608
|
+
|
|
609
|
+
The highest total, with every die showing its highest face, must be at most `_SPAWN_LIMIT`.
|
|
610
|
+
An expression that doesn't parse raises
|
|
611
|
+
[`ContentValidationError`][osrlib.errors.ContentValidationError] from
|
|
612
|
+
[`parse`][osrlib.core.dice.parse].
|
|
613
|
+
"""
|
|
614
|
+
highest = _highest_total(parse(expression))
|
|
615
|
+
if highest > _SPAWN_LIMIT:
|
|
616
|
+
raise ValueError(f"{expression!r} can roll {highest}, and a spawn creates at most {_SPAWN_LIMIT}")
|
|
617
|
+
return expression
|
|
618
|
+
|
|
619
|
+
|
|
597
620
|
class EncounterTableRow(_Model):
|
|
598
621
|
"""One d20 result on a wandering monster table: what appears, and how many.
|
|
599
622
|
|
|
@@ -603,6 +626,15 @@ class EncounterTableRow(_Model):
|
|
|
603
626
|
[`select_encounter_individuals`][osrlib.core.tables.select_encounter_individuals]. For an
|
|
604
627
|
[`NpcPartyEncounterEntry`][osrlib.core.tables.NpcPartyEncounterEntry], pass them to
|
|
605
628
|
[`generate_npc_party`][osrlib.core.npc.generate_npc_party].
|
|
629
|
+
|
|
630
|
+
A row creates at most 100 monsters or adventurers, so an adventure's own wandering monster
|
|
631
|
+
table can't spawn more at once than a
|
|
632
|
+
[`SpawnMonsters`][osrlib.crawl.commands.SpawnMonsters] command can.
|
|
633
|
+
|
|
634
|
+
Raises:
|
|
635
|
+
ContentValidationError: If `count_dice` is not a valid dice expression.
|
|
636
|
+
ValueError: If both `count_dice` and `count_fixed` are given, or neither, if `count_fixed`
|
|
637
|
+
is outside 1 to 100, or if `count_dice` can roll more than 100.
|
|
606
638
|
"""
|
|
607
639
|
|
|
608
640
|
model_config = ConfigDict(frozen=True)
|
|
@@ -620,11 +652,12 @@ class EncounterTableRow(_Model):
|
|
|
620
652
|
"""A dice expression for how many appear, like `"1d6"`, or `None` when the row has a fixed number.
|
|
621
653
|
|
|
622
654
|
Roll it with [`roll`][osrlib.core.dice.roll]. Use this count rather than the number appearing in the monster's
|
|
623
|
-
description, as the SRD's note on the dungeon tables says. Exactly one of this and `count_fixed` is set.
|
|
655
|
+
description, as the SRD's note on the dungeon tables says. Exactly one of this and `count_fixed` is set. The
|
|
656
|
+
expression's highest total must be at most 100, so `"1d100"` is legal and `"1d100+1"` isn't.
|
|
624
657
|
"""
|
|
625
658
|
|
|
626
|
-
count_fixed: int | None = None
|
|
627
|
-
"""A fixed number of individuals, or `None` when the row has a dice expression instead.
|
|
659
|
+
count_fixed: int | None = Field(default=None, ge=1, le=100)
|
|
660
|
+
"""A fixed number of individuals from 1 to 100, or `None` when the row has a dice expression instead.
|
|
628
661
|
|
|
629
662
|
Exactly one of this and `count_dice` is set.
|
|
630
663
|
"""
|
|
@@ -632,9 +665,7 @@ class EncounterTableRow(_Model):
|
|
|
632
665
|
@field_validator("count_dice")
|
|
633
666
|
@classmethod
|
|
634
667
|
def _dice_must_parse(cls, value: str | None) -> str | None:
|
|
635
|
-
if value is
|
|
636
|
-
parse(value)
|
|
637
|
-
return value
|
|
668
|
+
return value if value is None else _spawn_count_dice(value)
|
|
638
669
|
|
|
639
670
|
@model_validator(mode="after")
|
|
640
671
|
def _dice_or_fixed(self) -> EncounterTableRow:
|