osrlib 2.5.1__tar.gz → 2.7.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.7.0/PKG-INFO +197 -0
- osrlib-2.7.0/README.md +172 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/pyproject.toml +2 -2
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/__init__.py +10 -6
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/_descriptions.py +71 -5
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/character.py +36 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/classes.py +8 -4
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/events.py +50 -20
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/frozen.py +5 -3
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/items.py +8 -8
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/monsters.py +9 -3
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/npc.py +8 -6
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/ruleset.py +18 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/tables.py +11 -10
- osrlib-2.7.0/src/osrlib/crawl/_feature_handles.py +169 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_hauling.py +13 -10
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_items.py +5 -1
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_magic_items.py +52 -24
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_movement.py +3 -4
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_party_location.py +14 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_search.py +16 -10
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_treasure.py +30 -4
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/adventure.py +66 -3
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/battle.py +494 -108
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/commands.py +269 -101
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/content_pack.py +1 -1
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/dungeon.py +19 -8
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/encounter.py +21 -8
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/events.py +178 -16
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/session.py +72 -22
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/views.py +468 -60
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/messages.py +159 -92
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/persistence.py +33 -10
- osrlib-2.5.1/PKG-INFO +0 -147
- osrlib-2.5.1/README.md +0 -122
- {osrlib-2.5.1 → osrlib-2.7.0}/LICENSE +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/LICENSE-OGL.md +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/__init__.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/abilities.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/alignment.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/clock.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/combat.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/creature.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/dice.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/effects.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/rng.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/spells.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/treasure.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/core/validation.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/__init__.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_arrival.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_doors.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_gating.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_light.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_odometer.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_party_members.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_spells.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/_town.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/exploration.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/gates.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/interpreter.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/narrative.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/party.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/quests.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/stocking.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/crawl/triggers.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/LICENSE-OGL.md +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/__init__.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/abilities.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/classes.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/combat_tables.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/encounter_tables.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/equipment.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/languages.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/magic_items.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/monsters.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/spells.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/data/treasure.json +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/errors.py +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/py.typed +0 -0
- {osrlib-2.5.1 → osrlib-2.7.0}/src/osrlib/versioning.py +0 -0
osrlib-2.7.0/PKG-INFO
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: osrlib
|
|
3
|
+
Version: 2.7.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.7.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.7.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
|
"""
|
|
@@ -7,9 +7,19 @@ the docstring of its field. To read the docstrings, `_describe` parses the sourc
|
|
|
7
7
|
model and its base classes. It parses a module only when pydantic builds a schema, and only once, so importing osrlib
|
|
8
8
|
parses nothing.
|
|
9
9
|
|
|
10
|
-
Pydantic writes an enum's docstring as the description of
|
|
11
|
-
whose `__get_pydantic_json_schema__`
|
|
12
|
-
|
|
10
|
+
Pydantic writes a model's or an enum's class docstring as the description of its schema. Every osrlib enum subclasses
|
|
11
|
+
`_StrEnum`, whose `__get_pydantic_json_schema__` rewrites that description each time pydantic builds the enum's schema,
|
|
12
|
+
as `_describe` does for a model. A program such as an OpenAPI viewer renders the description as CommonMark, which
|
|
13
|
+
doesn't recognize the Google-style sections of a docstring: it joins the lines under `Attributes:` into one paragraph
|
|
14
|
+
and shows an indented fence as an indented code block. The description is therefore the docstring's text before its
|
|
15
|
+
first section, followed by its `Modes:`, `Rejections:`, and `Events:` sections, which describe what a command does on
|
|
16
|
+
the wire. Each kept section is its label on a line of its own, a blank line, and its body moved to the left margin, so
|
|
17
|
+
its lists and paragraphs render as they do on the documentation site. The other sections, such as `Attributes:`,
|
|
18
|
+
`Raises:`, and `Examples:`, are left out, because each property has its own description and the rest describe Python
|
|
19
|
+
use. A kept section whose body is only whitespace is left out too, and a schema whose description the rule empties has
|
|
20
|
+
no `description` key, as the schema of a class with no docstring has none. A section starts at a line at the left margin
|
|
21
|
+
that is one or more words and a colon when the line after it is indented, so a sentence that ends with a colon and
|
|
22
|
+
introduces text at the left margin isn't a section. Field descriptions keep their whole docstring.
|
|
13
23
|
|
|
14
24
|
A description reaches its reader as raw text, outside the documentation site, so `_describe` and `_StrEnum` reduce each
|
|
15
25
|
mkdocstrings cross-reference, like ``[`MoveParty`][osrlib.crawl.commands.MoveParty]``, to its label, `` `MoveParty` ``.
|
|
@@ -23,6 +33,7 @@ import ast
|
|
|
23
33
|
import inspect
|
|
24
34
|
import re
|
|
25
35
|
import sys
|
|
36
|
+
import textwrap
|
|
26
37
|
from enum import StrEnum
|
|
27
38
|
from functools import cache
|
|
28
39
|
from itertools import pairwise
|
|
@@ -117,6 +128,61 @@ def _reduce(schema: dict[str, Any]) -> None:
|
|
|
117
128
|
schema["description"] = _plain(description)
|
|
118
129
|
|
|
119
130
|
|
|
131
|
+
# A line that starts a docstring section when the line after it is indented: one or more words and a colon.
|
|
132
|
+
_LABEL = re.compile(r"[A-Z][A-Za-z ]*:")
|
|
133
|
+
|
|
134
|
+
# The sections a model's or an enum's description keeps, because they describe what a command does on the wire.
|
|
135
|
+
_KEPT = frozenset({"Modes", "Rejections", "Events"})
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _sectioned(description: str) -> str:
|
|
139
|
+
"""Return a class docstring as CommonMark: its text before the first section, then its wire sections.
|
|
140
|
+
|
|
141
|
+
A section starts at a line at the left margin that matches `_LABEL` when the line after it is indented, and it
|
|
142
|
+
runs to the next section or to the end of the docstring. The `Modes:`, `Rejections:`, and `Events:` sections are
|
|
143
|
+
kept, in the docstring's order, each as its label on a line of its own, a blank line, and its body moved to the
|
|
144
|
+
left margin. A kept section whose body is only whitespace is left out, and so is every other section. A docstring
|
|
145
|
+
with no sections is returned whole. `_sectioned` reduces the cross-references in each part.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
description: The class docstring as pydantic writes it, already cleaned by `inspect.cleandoc`.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
The description for the class's JSON Schema, which is empty when the docstring has nothing it keeps.
|
|
152
|
+
"""
|
|
153
|
+
lines = description.split("\n")
|
|
154
|
+
lead: list[str] = []
|
|
155
|
+
sections: list[tuple[str, list[str]]] = []
|
|
156
|
+
for line, following in zip(lines, [*lines[1:], ""], strict=True):
|
|
157
|
+
if _LABEL.fullmatch(line) and following.startswith(" "):
|
|
158
|
+
sections.append((line.removesuffix(":"), []))
|
|
159
|
+
elif sections:
|
|
160
|
+
sections[-1][1].append(line)
|
|
161
|
+
else:
|
|
162
|
+
lead.append(line)
|
|
163
|
+
if not sections:
|
|
164
|
+
return _plain(description)
|
|
165
|
+
parts = [_plain("\n".join(lead)).rstrip()]
|
|
166
|
+
for label, body in sections:
|
|
167
|
+
text = _plain(textwrap.dedent("\n".join(body))).strip("\n")
|
|
168
|
+
if label in _KEPT and text.strip():
|
|
169
|
+
parts.append(f"{label}:\n\n{text}")
|
|
170
|
+
return "\n\n".join(part for part in parts if part)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _reduce_class(schema: dict[str, Any]) -> None:
|
|
174
|
+
"""Rewrite a model's or an enum's top-level `description` as `_sectioned` gives it.
|
|
175
|
+
|
|
176
|
+
When the rewritten description is empty, the schema has no `description` key, as the schema of a class with no
|
|
177
|
+
docstring has none.
|
|
178
|
+
"""
|
|
179
|
+
if isinstance(description := schema.get("description"), str):
|
|
180
|
+
if text := _sectioned(description):
|
|
181
|
+
schema["description"] = text
|
|
182
|
+
else:
|
|
183
|
+
del schema["description"]
|
|
184
|
+
|
|
185
|
+
|
|
120
186
|
def _property_name(name: str, info: FieldInfo, mode: JsonSchemaMode) -> str:
|
|
121
187
|
"""Return the name of a field's property in a schema that uses aliases, as pydantic chooses it.
|
|
122
188
|
|
|
@@ -151,7 +217,7 @@ def _describe(cls: type[BaseModel], json_schema: JsonSchemaValue, handler: GetJs
|
|
|
151
217
|
reference to its definition.
|
|
152
218
|
"""
|
|
153
219
|
schema = handler.resolve_ref_schema(json_schema)
|
|
154
|
-
|
|
220
|
+
_reduce_class(schema)
|
|
155
221
|
fields = {name: name for name in cls.model_fields}
|
|
156
222
|
# A property named for a field's alias belongs to that field, even when another field has the same name.
|
|
157
223
|
fields.update({_property_name(name, info, handler.mode): name for name, info in cls.model_fields.items()})
|
|
@@ -177,5 +243,5 @@ class _StrEnum(StrEnum):
|
|
|
177
243
|
pydantic builds the definitions of a larger schema.
|
|
178
244
|
"""
|
|
179
245
|
json_schema = handler(schema)
|
|
180
|
-
|
|
246
|
+
_reduce_class(handler.resolve_ref_schema(json_schema))
|
|
181
247
|
return json_schema
|
|
@@ -109,8 +109,10 @@ from osrlib.core.items import (
|
|
|
109
109
|
Inventory,
|
|
110
110
|
ItemInstance,
|
|
111
111
|
ItemTemplate,
|
|
112
|
+
MagicItemInstance,
|
|
112
113
|
equip,
|
|
113
114
|
equipped_item_modifiers,
|
|
115
|
+
magic_item_template,
|
|
114
116
|
movement_rate_feet,
|
|
115
117
|
purchase,
|
|
116
118
|
validate_purchase,
|
|
@@ -809,6 +811,40 @@ class Character(_Model):
|
|
|
809
811
|
raise ContentValidationError(f"character document payload failed validation: {error}") from error
|
|
810
812
|
|
|
811
813
|
|
|
814
|
+
_TESTS_AS: Final = {"shield": "shield_plus_1", "worn_armour": "armour_plus_1"}
|
|
815
|
+
"""The +1 template that every test shows for a cursed item worn in each armour slot."""
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def _armour_as_tested(member: Character) -> Character:
|
|
819
|
+
"""Return the member as every test shows their armour, for an armour class that knows no more than a player does.
|
|
820
|
+
|
|
821
|
+
The OSE SRD says "All types of tests indicate that a cursed shield or suit of armour is enchanted with a +1
|
|
822
|
+
bonus. It is only when the armour is used in deadly combat that the curse is revealed." So in the copy this
|
|
823
|
+
returns, each worn cursed shield or suit that is unidentified and whose curse isn't revealed becomes a copy of
|
|
824
|
+
itself made from the +1 template, `shield_plus_1` or `armour_plus_1`, keeping its base item. Read
|
|
825
|
+
`armour_class` or `armour_class_ascending` from the copy for the number the item tests as. Everything else the
|
|
826
|
+
member wears counts as usual.
|
|
827
|
+
|
|
828
|
+
With nothing to mask, it returns the member itself. The copy is shallow and only read, so the member never
|
|
829
|
+
changes. The player view's armour class and the equipment choice of a generated NPC both read this, and the
|
|
830
|
+
attack rolls and every other rule read the member's real armour class.
|
|
831
|
+
"""
|
|
832
|
+
inventory = member.inventory
|
|
833
|
+
masked = {}
|
|
834
|
+
for slot, lookalike in _TESTS_AS.items():
|
|
835
|
+
worn = getattr(inventory, slot)
|
|
836
|
+
if (
|
|
837
|
+
isinstance(worn, MagicItemInstance)
|
|
838
|
+
and not worn.identified
|
|
839
|
+
and not worn.cursed_revealed
|
|
840
|
+
and magic_item_template(worn).cursed
|
|
841
|
+
):
|
|
842
|
+
masked[slot] = worn.model_copy(update={"template_id": lookalike})
|
|
843
|
+
if not masked:
|
|
844
|
+
return member
|
|
845
|
+
return member.model_copy(update={"inventory": inventory.model_copy(update=masked)})
|
|
846
|
+
|
|
847
|
+
|
|
812
848
|
def party_to_document(characters: Sequence[Character]) -> dict[str, object]:
|
|
813
849
|
"""Return a group of characters as one JSON-ready document, stamped with its schema and engine versions.
|
|
814
850
|
|
|
@@ -999,7 +999,9 @@ def thief_skill_check(
|
|
|
999
999
|
door, or picking a pocket. It rolls and returns the result, and does nothing else. It emits no
|
|
1000
1000
|
events, and it doesn't decide what the players may see. If you show players only what their
|
|
1001
1001
|
characters know, you decide what to reveal. In a session, the engine calls it and emits the
|
|
1002
|
-
events for you when it resolves commands like [`PickLock`][osrlib.crawl.commands.PickLock]
|
|
1002
|
+
events for you when it resolves commands like [`PickLock`][osrlib.crawl.commands.PickLock], and
|
|
1003
|
+
when a thief hides and back-stabs in a battle round, as
|
|
1004
|
+
[`BattleDeclaration.back_stab`][osrlib.crawl.commands.BattleDeclaration.back_stab] describes.
|
|
1003
1005
|
|
|
1004
1006
|
For a skill in [`PERCENTILE_THIEF_SKILLS`][osrlib.core.classes.PERCENTILE_THIEF_SKILLS], it
|
|
1005
1007
|
rolls d%, and the check succeeds on a roll equal to or under the chance for the thief's level.
|
|
@@ -1019,9 +1021,11 @@ def thief_skill_check(
|
|
|
1019
1021
|
`"hear_noise"`.
|
|
1020
1022
|
modifier_pct: A percentage added to the chance before rolling. Make it negative to make
|
|
1021
1023
|
the attempt harder. Ignored for `"hear_noise"`.
|
|
1022
|
-
stream: The stream to draw from
|
|
1023
|
-
`streams.get(`[`EXPLORATION_STREAM`][osrlib.crawl.session.EXPLORATION_STREAM]`)
|
|
1024
|
-
|
|
1024
|
+
stream: The stream to draw from. A session draws a thief check outside a battle from
|
|
1025
|
+
`streams.get(`[`EXPLORATION_STREAM`][osrlib.crawl.session.EXPLORATION_STREAM]`)`, and a
|
|
1026
|
+
battle's hide in shadows and move silently rolls from
|
|
1027
|
+
`streams.get(`[`COMBAT_STREAM`][osrlib.core.combat.COMBAT_STREAM]`)`. It advances by one
|
|
1028
|
+
draw.
|
|
1025
1029
|
|
|
1026
1030
|
Returns:
|
|
1027
1031
|
The roll, the chance it was checked against, and whether it succeeded.
|