osrlib 2.4.0__tar.gz → 2.5.1__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.4.0 → osrlib-2.5.1}/PKG-INFO +1 -1
- {osrlib-2.4.0 → osrlib-2.5.1}/pyproject.toml +1 -1
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/__init__.py +1 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/__init__.py +23 -0
- osrlib-2.5.1/src/osrlib/core/_descriptions.py +181 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/abilities.py +49 -16
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/alignment.py +2 -2
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/character.py +259 -76
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/classes.py +118 -56
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/clock.py +11 -9
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/combat.py +157 -78
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/creature.py +19 -1
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/dice.py +18 -7
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/effects.py +104 -50
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/events.py +81 -39
- osrlib-2.5.1/src/osrlib/core/frozen.py +267 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/items.py +283 -134
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/monsters.py +162 -39
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/npc.py +21 -8
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/rng.py +41 -18
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/ruleset.py +6 -5
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/spells.py +168 -71
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/tables.py +71 -38
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/treasure.py +65 -57
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/core/validation.py +4 -2
- osrlib-2.5.1/src/osrlib/crawl/_arrival.py +478 -0
- osrlib-2.5.1/src/osrlib/crawl/_doors.py +345 -0
- osrlib-2.5.1/src/osrlib/crawl/_gating.py +62 -0
- osrlib-2.5.1/src/osrlib/crawl/_hauling.py +494 -0
- osrlib-2.5.1/src/osrlib/crawl/_items.py +226 -0
- osrlib-2.5.1/src/osrlib/crawl/_light.py +302 -0
- osrlib-2.5.1/src/osrlib/crawl/_magic_items.py +673 -0
- osrlib-2.5.1/src/osrlib/crawl/_movement.py +204 -0
- osrlib-2.5.1/src/osrlib/crawl/_odometer.py +25 -0
- osrlib-2.5.1/src/osrlib/crawl/_party_location.py +58 -0
- osrlib-2.5.1/src/osrlib/crawl/_party_members.py +103 -0
- osrlib-2.5.1/src/osrlib/crawl/_search.py +255 -0
- osrlib-2.5.1/src/osrlib/crawl/_spells.py +280 -0
- osrlib-2.5.1/src/osrlib/crawl/_town.py +254 -0
- osrlib-2.5.1/src/osrlib/crawl/_treasure.py +222 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/adventure.py +274 -88
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/battle.py +902 -300
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/commands.py +404 -207
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/content_pack.py +73 -19
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/dungeon.py +105 -63
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/encounter.py +216 -95
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/events.py +132 -38
- osrlib-2.5.1/src/osrlib/crawl/exploration.py +958 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/gates.py +6 -5
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/interpreter.py +6 -7
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/narrative.py +4 -2
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/party.py +3 -2
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/quests.py +5 -4
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/session.py +214 -94
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/stocking.py +22 -22
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/triggers.py +10 -9
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/views.py +284 -60
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/__init__.py +29 -18
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/magic_items.json +62 -16
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/monsters.json +699 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/spells.json +3 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/messages.py +18 -4
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/persistence.py +76 -30
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/versioning.py +11 -9
- osrlib-2.4.0/src/osrlib/crawl/exploration.py +0 -4559
- {osrlib-2.4.0 → osrlib-2.5.1}/LICENSE +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/LICENSE-OGL.md +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/README.md +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/crawl/__init__.py +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/LICENSE-OGL.md +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/abilities.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/classes.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/combat_tables.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/encounter_tables.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/equipment.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/languages.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/data/treasure.json +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/errors.py +0 -0
- {osrlib-2.4.0 → osrlib-2.5.1}/src/osrlib/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "osrlib"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.5.1"
|
|
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
|
|
@@ -26,6 +26,7 @@ Kernel modules never import from `osrlib.crawl`, so you can use them without it.
|
|
|
26
26
|
| [`osrlib.core.clock`][] | Count game time in rounds, and report each turn and day that passes. |
|
|
27
27
|
| [`osrlib.core.alignment`][] | The three alignments that characters and monsters share. |
|
|
28
28
|
| [`osrlib.core.validation`][] | The refusal a rules check returns instead of raising an exception. |
|
|
29
|
+
| [`osrlib.core.frozen`][] | The read-only mapping in frozen content, like an ability's numbers or a level's edges. |
|
|
29
30
|
| [`osrlib.core.abilities`][] | Look up the modifier or chance an ability score gives, and make ability checks. |
|
|
30
31
|
| [`osrlib.core.classes`][] | Read a class's titles and level table, and award experience points (XP). |
|
|
31
32
|
| [`osrlib.core.monsters`][] | Read monster templates, and spawn a monster with rolled hit points. |
|
|
@@ -32,6 +32,9 @@ The kernel has these modules, in the order you usually need them:
|
|
|
32
32
|
[`Rejection`][osrlib.core.validation.Rejection] a rules check returns instead of raising, with
|
|
33
33
|
a code for the reason. A check returns a list of them, and an empty list means the action is
|
|
34
34
|
legal.
|
|
35
|
+
- [`osrlib.core.frozen`][osrlib.core.frozen]: the [`FrozenMap`][osrlib.core.frozen.FrozenMap] that
|
|
36
|
+
the frozen content uses for each field that maps names to values, like a monster ability's
|
|
37
|
+
`params` or a level's `edges`. You read one like a dict, and nothing can change it.
|
|
35
38
|
- [`osrlib.core.abilities`][osrlib.core.abilities]: look up the modifiers an ability score from 3
|
|
36
39
|
to 18 gives, make ability checks, and adjust a set of scores.
|
|
37
40
|
- [`osrlib.core.classes`][osrlib.core.classes]: read a class's titles and level table, award
|
|
@@ -91,3 +94,23 @@ assert clock.rounds == 60
|
|
|
91
94
|
assert [(crossing.unit, crossing.index) for crossing in crossings] == [(TimeUnit.TURN, 1)]
|
|
92
95
|
```
|
|
93
96
|
"""
|
|
97
|
+
|
|
98
|
+
import importlib
|
|
99
|
+
from types import ModuleType
|
|
100
|
+
|
|
101
|
+
_LOADED_ON_FIRST_USE = frozenset({"character", "spells"})
|
|
102
|
+
"""The kernel modules that an annotation reads as an attribute of this package.
|
|
103
|
+
|
|
104
|
+
`osrlib.core.classes` names `Character` and `SpellCatalog` in its signatures, and `osrlib.core.items` names
|
|
105
|
+
`Character`. Both modules load early, inside the modules that `character` and `spells` need. So neither can import
|
|
106
|
+
`character` or `spells`, even at its end. That import would run while a module that `character` or `spells` needs is
|
|
107
|
+
half loaded. The annotations read the types through this package instead. The package loads the module the first
|
|
108
|
+
time something asks for a signature.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def __getattr__(name: str) -> ModuleType:
|
|
113
|
+
"""Load one of the modules in `_LOADED_ON_FIRST_USE` when it's read as an attribute before anything imports it."""
|
|
114
|
+
if name in _LOADED_ON_FIRST_USE:
|
|
115
|
+
return importlib.import_module(f"{__name__}.{name}")
|
|
116
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""The descriptions in the JSON Schema of an osrlib model: each field's docstring, as plain Markdown.
|
|
2
|
+
|
|
3
|
+
osrlib documents a field with a string on the line after it. osrlib's models don't turn on pydantic's
|
|
4
|
+
`use_attribute_docstrings`, so pydantic doesn't read that string. Each time pydantic builds the JSON Schema of a model,
|
|
5
|
+
`_Model.__get_pydantic_json_schema__` calls `_describe`, which gives each property without a `Field(description=...)`
|
|
6
|
+
the docstring of its field. To read the docstrings, `_describe` parses the source of the modules that define the
|
|
7
|
+
model and its base classes. It parses a module only when pydantic builds a schema, and only once, so importing osrlib
|
|
8
|
+
parses nothing.
|
|
9
|
+
|
|
10
|
+
Pydantic writes an enum's docstring as the description of the enum's schema. Every osrlib enum subclasses `_StrEnum`,
|
|
11
|
+
whose `__get_pydantic_json_schema__` reduces the cross-references in that description each time pydantic builds the
|
|
12
|
+
enum's schema.
|
|
13
|
+
|
|
14
|
+
A description reaches its reader as raw text, outside the documentation site, so `_describe` and `_StrEnum` reduce each
|
|
15
|
+
mkdocstrings cross-reference, like ``[`MoveParty`][osrlib.crawl.commands.MoveParty]``, to its label, `` `MoveParty` ``.
|
|
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.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import ast
|
|
23
|
+
import inspect
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
from enum import StrEnum
|
|
27
|
+
from functools import cache
|
|
28
|
+
from itertools import pairwise
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from pydantic import AliasChoices, BaseModel, GetJsonSchemaHandler
|
|
32
|
+
from pydantic.fields import FieldInfo
|
|
33
|
+
from pydantic.json_schema import JsonSchemaMode, JsonSchemaValue
|
|
34
|
+
from pydantic_core import CoreSchema
|
|
35
|
+
|
|
36
|
+
# A fenced code block or a span in two or more backticks.
|
|
37
|
+
_LITERAL = re.compile(r"(```.*?```|~~~.*?~~~|``.+?``)", re.DOTALL)
|
|
38
|
+
|
|
39
|
+
# A span in single backticks, or a cross-reference: a label in brackets, then a target in brackets. The label is text,
|
|
40
|
+
# code spans, or both, like [`MoveParty`][osrlib.crawl.commands.MoveParty], [the rejection code
|
|
41
|
+
# reference][rejection-codes], or [a `MoveParty` command][osrlib.crawl.commands.MoveParty]. The expression matches the
|
|
42
|
+
# span or the cross-reference that starts first, so it never reads brackets inside code as a cross-reference.
|
|
43
|
+
_SPAN_OR_REFERENCE = re.compile(r"(`[^`\n]+`)|\[((?:[^\[\]`]|`[^`\n]+`)+)\]\[[^\]\s]+\]")
|
|
44
|
+
|
|
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
|
+
|
|
53
|
+
def _plain(text: str) -> str:
|
|
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
|
+
"""
|
|
61
|
+
if "][" not in text:
|
|
62
|
+
return text
|
|
63
|
+
parts = _LITERAL.split(text)
|
|
64
|
+
parts[::2] = [_JOIN.sub("", _SPAN_OR_REFERENCE.sub(_mark_label, part)).replace(_EDGE, "") for part in parts[::2]]
|
|
65
|
+
return "".join(parts)
|
|
66
|
+
|
|
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
|
+
|
|
73
|
+
@cache
|
|
74
|
+
def _module_docstrings(module_name: str) -> dict[str, dict[str, str]]:
|
|
75
|
+
"""Map the qualified name of each class in a module to the plain docstrings of the fields it declares.
|
|
76
|
+
|
|
77
|
+
For a module whose source can't be read, like one installed as bytecode alone, the mapping is empty. The cache lasts
|
|
78
|
+
as long as the process, so after `importlib.reload` reloads a module, its schemas still have the docstrings from
|
|
79
|
+
before the reload.
|
|
80
|
+
"""
|
|
81
|
+
try:
|
|
82
|
+
tree = ast.parse(inspect.getsource(sys.modules[module_name]))
|
|
83
|
+
except KeyError, OSError, TypeError, SyntaxError:
|
|
84
|
+
return {}
|
|
85
|
+
classes: dict[str, dict[str, str]] = {}
|
|
86
|
+
|
|
87
|
+
def collect(body: list[ast.stmt], prefix: str) -> None:
|
|
88
|
+
for node in body:
|
|
89
|
+
if isinstance(node, ast.ClassDef):
|
|
90
|
+
classes[prefix + node.name] = {
|
|
91
|
+
statement.target.id: _plain(inspect.cleandoc(following.value.value))
|
|
92
|
+
for statement, following in pairwise(node.body)
|
|
93
|
+
if isinstance(statement, ast.AnnAssign)
|
|
94
|
+
and isinstance(statement.target, ast.Name)
|
|
95
|
+
and isinstance(following, ast.Expr)
|
|
96
|
+
and isinstance(following.value, ast.Constant)
|
|
97
|
+
and isinstance(following.value.value, str)
|
|
98
|
+
}
|
|
99
|
+
collect(node.body, f"{prefix}{node.name}.")
|
|
100
|
+
|
|
101
|
+
collect(tree.body, "")
|
|
102
|
+
return classes
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _field_docstrings(cls: type[BaseModel]) -> dict[str, str]:
|
|
106
|
+
"""Return the plain docstring of each field, from the class or from the nearest ancestor that documents it."""
|
|
107
|
+
docstrings: dict[str, str] = {}
|
|
108
|
+
for ancestor in reversed(cls.__mro__):
|
|
109
|
+
if ancestor is not BaseModel and issubclass(ancestor, BaseModel):
|
|
110
|
+
docstrings.update(_module_docstrings(ancestor.__module__).get(ancestor.__qualname__, {}))
|
|
111
|
+
return docstrings
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _reduce(schema: dict[str, Any]) -> None:
|
|
115
|
+
"""Reduce the cross-references in a schema's top-level `description`."""
|
|
116
|
+
if isinstance(description := schema.get("description"), str):
|
|
117
|
+
schema["description"] = _plain(description)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _property_name(name: str, info: FieldInfo, mode: JsonSchemaMode) -> str:
|
|
121
|
+
"""Return the name of a field's property in a schema that uses aliases, as pydantic chooses it.
|
|
122
|
+
|
|
123
|
+
The alias for the mode is a name, an `AliasPath`, or an `AliasChoices`. For an `AliasChoices`, pydantic uses the
|
|
124
|
+
first choice that's a path of one name, like `"flat"` in `AliasChoices(AliasPath("outer", "inner"), "flat")`. For
|
|
125
|
+
an `AliasPath` alone, even a path of one name, and for an `AliasChoices` with no such choice, it uses the field's
|
|
126
|
+
name.
|
|
127
|
+
"""
|
|
128
|
+
alias = info.validation_alias if mode == "validation" else info.serialization_alias
|
|
129
|
+
if alias is None:
|
|
130
|
+
alias = info.alias
|
|
131
|
+
if isinstance(alias, str):
|
|
132
|
+
return alias
|
|
133
|
+
if isinstance(alias, AliasChoices):
|
|
134
|
+
for path in alias.convert_to_aliases():
|
|
135
|
+
if len(path) == 1 and isinstance(path[0], str):
|
|
136
|
+
return path[0]
|
|
137
|
+
return name
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _describe(cls: type[BaseModel], json_schema: JsonSchemaValue, handler: GetJsonSchemaHandler) -> None:
|
|
141
|
+
"""Give a model's JSON Schema the docstring of each field, and reduce the cross-references in its descriptions.
|
|
142
|
+
|
|
143
|
+
A field declared with `Field(description=...)` has that description in the schema instead, with its cross-references
|
|
144
|
+
reduced. A property can be named for the field or for its alias, so the schema is described both when it uses
|
|
145
|
+
aliases and when it doesn't.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
cls: The model.
|
|
149
|
+
json_schema: The model's JSON Schema, or a reference to it. `_describe` changes the schema in place.
|
|
150
|
+
handler: The handler pydantic passed to the model's `__get_pydantic_json_schema__`, which resolves a
|
|
151
|
+
reference to its definition.
|
|
152
|
+
"""
|
|
153
|
+
schema = handler.resolve_ref_schema(json_schema)
|
|
154
|
+
_reduce(schema)
|
|
155
|
+
fields = {name: name for name in cls.model_fields}
|
|
156
|
+
# A property named for a field's alias belongs to that field, even when another field has the same name.
|
|
157
|
+
fields.update({_property_name(name, info, handler.mode): name for name, info in cls.model_fields.items()})
|
|
158
|
+
docstrings = _field_docstrings(cls)
|
|
159
|
+
properties: dict[str, Any] = schema.get("properties", {})
|
|
160
|
+
for key, prop in properties.items():
|
|
161
|
+
name = fields.get(key)
|
|
162
|
+
if name is not None and cls.model_fields[name].description is None and name in docstrings:
|
|
163
|
+
prop["description"] = docstrings[name]
|
|
164
|
+
else:
|
|
165
|
+
_reduce(prop)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class _StrEnum(StrEnum):
|
|
169
|
+
"""The base class of every osrlib enum. It reduces the cross-references in the description of the enum's schema."""
|
|
170
|
+
|
|
171
|
+
@classmethod
|
|
172
|
+
def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler, /) -> JsonSchemaValue:
|
|
173
|
+
"""Return the enum's JSON Schema, with each cross-reference in its description reduced to its label.
|
|
174
|
+
|
|
175
|
+
Pydantic calls this each time it builds the enum's schema, after it writes the enum's docstring as the
|
|
176
|
+
description. The call reads and changes only the enum's schema, so it doesn't depend on the order in which
|
|
177
|
+
pydantic builds the definitions of a larger schema.
|
|
178
|
+
"""
|
|
179
|
+
json_schema = handler(schema)
|
|
180
|
+
_reduce(handler.resolve_ref_schema(json_schema))
|
|
181
|
+
return json_schema
|
|
@@ -63,10 +63,10 @@ assert (check.roll, check.success) == (18, False)
|
|
|
63
63
|
```
|
|
64
64
|
"""
|
|
65
65
|
|
|
66
|
-
from
|
|
67
|
-
|
|
68
|
-
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
66
|
+
from pydantic import ConfigDict, Field, model_validator
|
|
69
67
|
|
|
68
|
+
from osrlib.core._descriptions import _StrEnum
|
|
69
|
+
from osrlib.core.frozen import _Model
|
|
70
70
|
from osrlib.core.rng import RngStream
|
|
71
71
|
from osrlib.core.validation import Rejection
|
|
72
72
|
|
|
@@ -121,7 +121,7 @@ rolled below 9 is legal, and the trade can't lower it further.
|
|
|
121
121
|
"""
|
|
122
122
|
|
|
123
123
|
|
|
124
|
-
class AbilityScore(
|
|
124
|
+
class AbilityScore(_StrEnum):
|
|
125
125
|
"""Which of the six abilities a score belongs to.
|
|
126
126
|
|
|
127
127
|
Use these as the keys of a score dictionary, which is how every function here and in
|
|
@@ -152,7 +152,7 @@ class AbilityScore(StrEnum):
|
|
|
152
152
|
"""Charisma: how monsters and NPCs react, and how many retainers the character can keep, and how loyal they are."""
|
|
153
153
|
|
|
154
154
|
|
|
155
|
-
class Literacy(
|
|
155
|
+
class Literacy(_StrEnum):
|
|
156
156
|
"""How well a character reads and writes, which their intelligence score sets.
|
|
157
157
|
|
|
158
158
|
Read it off [`AbilityTables.literacy`][osrlib.core.abilities.AbilityTables.literacy], passing the
|
|
@@ -170,7 +170,7 @@ class Literacy(StrEnum):
|
|
|
170
170
|
"""Can read and write the character's native languages, at intelligence 9 or above."""
|
|
171
171
|
|
|
172
172
|
|
|
173
|
-
class ScoreBand(
|
|
173
|
+
class ScoreBand(_Model):
|
|
174
174
|
"""The run of scores one table row covers, like 4 to 5.
|
|
175
175
|
|
|
176
176
|
The SRD prints its modifier tables in bands instead of one row per score, and osrlib
|
|
@@ -335,7 +335,7 @@ def _validate_coverage(rows: tuple[ScoreBand, ...], table: str) -> None:
|
|
|
335
335
|
raise ValueError(f"{table} table bands must end at {MAX_SCORE}")
|
|
336
336
|
|
|
337
337
|
|
|
338
|
-
class AbilityTables(
|
|
338
|
+
class AbilityTables(_Model):
|
|
339
339
|
"""The SRD's ability tables, and the accessors that read a score out of them.
|
|
340
340
|
|
|
341
341
|
Get one from [`load_ability_tables`][osrlib.data.load_ability_tables], which loads the
|
|
@@ -763,7 +763,7 @@ class AbilityTables(BaseModel):
|
|
|
763
763
|
return self._row(self.prime_requisite, score).xp_modifier_pct
|
|
764
764
|
|
|
765
765
|
|
|
766
|
-
class AbilityCheckResult(
|
|
766
|
+
class AbilityCheckResult(_Model):
|
|
767
767
|
"""How an ability check turned out, including the die roll so you can show it.
|
|
768
768
|
|
|
769
769
|
[`ability_check`][osrlib.core.abilities.ability_check] returns one.
|
|
@@ -788,7 +788,7 @@ class AbilityCheckResult(BaseModel):
|
|
|
788
788
|
"""
|
|
789
789
|
|
|
790
790
|
|
|
791
|
-
class OpenDoorsResult(
|
|
791
|
+
class OpenDoorsResult(_Model):
|
|
792
792
|
"""How an attempt to force a door turned out, including the die roll so you can show it.
|
|
793
793
|
|
|
794
794
|
[`open_doors_check`][osrlib.core.abilities.open_doors_check] returns one.
|
|
@@ -908,7 +908,7 @@ def open_doors_check(chance: int, stream: RngStream) -> OpenDoorsResult:
|
|
|
908
908
|
_LOWERABLE = (AbilityScore.STR, AbilityScore.INT, AbilityScore.WIS)
|
|
909
909
|
|
|
910
910
|
|
|
911
|
-
class AbilityAdjustment(
|
|
911
|
+
class AbilityAdjustment(_Model):
|
|
912
912
|
"""A proposed trade of ability points, made once while a character is being created.
|
|
913
913
|
|
|
914
914
|
Build one from what the player chose, check it with
|
|
@@ -990,7 +990,9 @@ def validate_adjustment(
|
|
|
990
990
|
or raised above [`MAX_SCORE`][osrlib.core.abilities.MAX_SCORE].
|
|
991
991
|
|
|
992
992
|
Args:
|
|
993
|
-
scores: The rolled scores, with all six abilities present
|
|
993
|
+
scores: The rolled scores, with all six abilities present, each from
|
|
994
|
+
[`MIN_SCORE`][osrlib.core.abilities.MIN_SCORE] to
|
|
995
|
+
[`MAX_SCORE`][osrlib.core.abilities.MAX_SCORE].
|
|
994
996
|
adjustment: The trade the player proposed.
|
|
995
997
|
prime_requisites: The chosen class's prime requisites, from
|
|
996
998
|
[`ClassDefinition`][osrlib.core.classes.ClassDefinition].
|
|
@@ -1002,6 +1004,11 @@ def validate_adjustment(
|
|
|
1002
1004
|
trade is legal. A single proposal can break several rules at once, so expect more
|
|
1003
1005
|
than one.
|
|
1004
1006
|
|
|
1007
|
+
Raises:
|
|
1008
|
+
ValueError: If `scores` is missing an ability, or has a score below 3 or above 18. No
|
|
1009
|
+
character can roll such scores, so there's no trade to judge. The message includes
|
|
1010
|
+
the ability.
|
|
1011
|
+
|
|
1005
1012
|
Examples:
|
|
1006
1013
|
```python
|
|
1007
1014
|
from osrlib.core.abilities import AbilityAdjustment, AbilityScore, validate_adjustment
|
|
@@ -1029,6 +1036,31 @@ def validate_adjustment(
|
|
|
1029
1036
|
]
|
|
1030
1037
|
```
|
|
1031
1038
|
"""
|
|
1039
|
+
_check_scores(scores)
|
|
1040
|
+
return _adjustment_rejections(adjustment, prime_requisites, may_not_lower, scores)
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _check_scores(scores: dict[AbilityScore, int]) -> None:
|
|
1044
|
+
"""Raise `ValueError` unless `scores` has all six abilities, each from `MIN_SCORE` to `MAX_SCORE`."""
|
|
1045
|
+
missing = [ability.value for ability in AbilityScore if ability not in scores]
|
|
1046
|
+
if missing:
|
|
1047
|
+
raise ValueError(f"scores must include all six abilities; missing {missing}")
|
|
1048
|
+
for ability, score in scores.items():
|
|
1049
|
+
if not MIN_SCORE <= score <= MAX_SCORE:
|
|
1050
|
+
raise ValueError(f"{ability} must be in {MIN_SCORE}-{MAX_SCORE}, got {score}")
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def _adjustment_rejections(
|
|
1054
|
+
adjustment: AbilityAdjustment,
|
|
1055
|
+
prime_requisites: tuple[AbilityScore, ...],
|
|
1056
|
+
may_not_lower: tuple[AbilityScore, ...],
|
|
1057
|
+
scores: dict[AbilityScore, int] | None,
|
|
1058
|
+
) -> list[Rejection]:
|
|
1059
|
+
"""Return the rules a trade breaks, in the order `validate_adjustment` documents.
|
|
1060
|
+
|
|
1061
|
+
With `scores` of `None`, it skips the floor and the cap, the two rules that read a score, so
|
|
1062
|
+
`create_character` can judge the rest of a trade before it rolls.
|
|
1063
|
+
"""
|
|
1032
1064
|
rejections: list[Rejection] = []
|
|
1033
1065
|
for ability, amount in adjustment.lowered.items():
|
|
1034
1066
|
if ability not in _LOWERABLE:
|
|
@@ -1043,7 +1075,7 @@ def validate_adjustment(
|
|
|
1043
1075
|
rejections.append(
|
|
1044
1076
|
Rejection(code="creation.adjustment.reduction_not_even", params={"ability": ability, "amount": amount})
|
|
1045
1077
|
)
|
|
1046
|
-
if scores[ability] - amount < ADJUSTMENT_FLOOR:
|
|
1078
|
+
if scores is not None and scores[ability] - amount < ADJUSTMENT_FLOOR:
|
|
1047
1079
|
rejections.append(
|
|
1048
1080
|
Rejection(
|
|
1049
1081
|
code="creation.adjustment.below_floor",
|
|
@@ -1055,7 +1087,7 @@ def validate_adjustment(
|
|
|
1055
1087
|
rejections.append(
|
|
1056
1088
|
Rejection(code="creation.adjustment.raise_not_prime_requisite", params={"ability": ability})
|
|
1057
1089
|
)
|
|
1058
|
-
elif scores[ability] + amount > MAX_SCORE:
|
|
1090
|
+
elif scores is not None and scores[ability] + amount > MAX_SCORE:
|
|
1059
1091
|
rejections.append(
|
|
1060
1092
|
Rejection(
|
|
1061
1093
|
code="creation.adjustment.above_cap",
|
|
@@ -1093,8 +1125,8 @@ def apply_adjustment(
|
|
|
1093
1125
|
`AbilityAdjustment` as its `adjustment` argument and applies it for you.
|
|
1094
1126
|
|
|
1095
1127
|
Args:
|
|
1096
|
-
scores: The rolled scores, with all six abilities present. This
|
|
1097
|
-
changed. The adjusted scores come back in a new one.
|
|
1128
|
+
scores: The rolled scores, with all six abilities present, each from 3 to 18. This
|
|
1129
|
+
dictionary isn't changed. The adjusted scores come back in a new one.
|
|
1098
1130
|
adjustment: The trade to apply.
|
|
1099
1131
|
prime_requisites: The chosen class's prime requisites.
|
|
1100
1132
|
may_not_lower: Abilities this class forbids lowering.
|
|
@@ -1106,7 +1138,8 @@ def apply_adjustment(
|
|
|
1106
1138
|
Raises:
|
|
1107
1139
|
ValueError: If the trade breaks any rule
|
|
1108
1140
|
[`validate_adjustment`][osrlib.core.abilities.validate_adjustment] checks. The
|
|
1109
|
-
message includes the rejection codes.
|
|
1141
|
+
message includes the rejection codes. Also if `scores` is missing an ability, or
|
|
1142
|
+
has a score below 3 or above 18, as `validate_adjustment` raises.
|
|
1110
1143
|
|
|
1111
1144
|
Examples:
|
|
1112
1145
|
```python
|
|
@@ -19,14 +19,14 @@ Alignment is in a separate module so that the character models and the monster m
|
|
|
19
19
|
can both import it without importing each other.
|
|
20
20
|
"""
|
|
21
21
|
|
|
22
|
-
from
|
|
22
|
+
from osrlib.core._descriptions import _StrEnum
|
|
23
23
|
|
|
24
24
|
__all__ = [
|
|
25
25
|
"Alignment",
|
|
26
26
|
]
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
class Alignment(
|
|
29
|
+
class Alignment(_StrEnum):
|
|
30
30
|
"""The cosmic principle a creature follows: law, neutrality, or chaos.
|
|
31
31
|
|
|
32
32
|
Use a member by name (`Alignment.LAWFUL`) when you write the value yourself, and call
|