osrlib 2.4.0__tar.gz → 2.5.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.
Files changed (79) hide show
  1. {osrlib-2.4.0 → osrlib-2.5.0}/PKG-INFO +1 -1
  2. {osrlib-2.4.0 → osrlib-2.5.0}/pyproject.toml +1 -1
  3. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/__init__.py +1 -0
  4. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/__init__.py +23 -0
  5. osrlib-2.5.0/src/osrlib/core/_descriptions.py +161 -0
  6. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/abilities.py +49 -16
  7. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/alignment.py +2 -2
  8. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/character.py +259 -76
  9. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/classes.py +118 -56
  10. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/clock.py +11 -9
  11. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/combat.py +157 -78
  12. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/creature.py +19 -1
  13. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/dice.py +13 -7
  14. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/effects.py +104 -50
  15. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/events.py +81 -39
  16. osrlib-2.5.0/src/osrlib/core/frozen.py +267 -0
  17. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/items.py +283 -134
  18. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/monsters.py +162 -39
  19. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/npc.py +21 -8
  20. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/rng.py +41 -18
  21. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/ruleset.py +6 -5
  22. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/spells.py +168 -71
  23. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/tables.py +34 -32
  24. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/treasure.py +65 -57
  25. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/core/validation.py +4 -2
  26. osrlib-2.5.0/src/osrlib/crawl/_arrival.py +478 -0
  27. osrlib-2.5.0/src/osrlib/crawl/_doors.py +345 -0
  28. osrlib-2.5.0/src/osrlib/crawl/_gating.py +62 -0
  29. osrlib-2.5.0/src/osrlib/crawl/_hauling.py +494 -0
  30. osrlib-2.5.0/src/osrlib/crawl/_items.py +226 -0
  31. osrlib-2.5.0/src/osrlib/crawl/_light.py +302 -0
  32. osrlib-2.5.0/src/osrlib/crawl/_magic_items.py +673 -0
  33. osrlib-2.5.0/src/osrlib/crawl/_movement.py +204 -0
  34. osrlib-2.5.0/src/osrlib/crawl/_odometer.py +25 -0
  35. osrlib-2.5.0/src/osrlib/crawl/_party_location.py +58 -0
  36. osrlib-2.5.0/src/osrlib/crawl/_party_members.py +103 -0
  37. osrlib-2.5.0/src/osrlib/crawl/_search.py +255 -0
  38. osrlib-2.5.0/src/osrlib/crawl/_spells.py +280 -0
  39. osrlib-2.5.0/src/osrlib/crawl/_town.py +254 -0
  40. osrlib-2.5.0/src/osrlib/crawl/_treasure.py +222 -0
  41. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/adventure.py +274 -88
  42. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/battle.py +902 -300
  43. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/commands.py +359 -192
  44. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/content_pack.py +73 -19
  45. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/dungeon.py +69 -50
  46. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/encounter.py +216 -95
  47. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/events.py +132 -38
  48. osrlib-2.5.0/src/osrlib/crawl/exploration.py +958 -0
  49. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/gates.py +6 -5
  50. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/interpreter.py +6 -7
  51. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/narrative.py +4 -2
  52. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/party.py +3 -2
  53. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/quests.py +5 -4
  54. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/session.py +214 -94
  55. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/stocking.py +22 -22
  56. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/triggers.py +10 -9
  57. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/views.py +284 -60
  58. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/__init__.py +29 -18
  59. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/magic_items.json +62 -16
  60. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/monsters.json +699 -0
  61. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/spells.json +3 -0
  62. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/messages.py +18 -4
  63. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/persistence.py +76 -30
  64. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/versioning.py +11 -9
  65. osrlib-2.4.0/src/osrlib/crawl/exploration.py +0 -4559
  66. {osrlib-2.4.0 → osrlib-2.5.0}/LICENSE +0 -0
  67. {osrlib-2.4.0 → osrlib-2.5.0}/LICENSE-OGL.md +0 -0
  68. {osrlib-2.4.0 → osrlib-2.5.0}/README.md +0 -0
  69. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/crawl/__init__.py +0 -0
  70. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/LICENSE-OGL.md +0 -0
  71. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/abilities.json +0 -0
  72. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/classes.json +0 -0
  73. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/combat_tables.json +0 -0
  74. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/encounter_tables.json +0 -0
  75. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/equipment.json +0 -0
  76. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/languages.json +0 -0
  77. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/data/treasure.json +0 -0
  78. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/errors.py +0 -0
  79. {osrlib-2.4.0 → osrlib-2.5.0}/src/osrlib/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: osrlib
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: B/X (1981 Basic/Expert) tabletop RPG rules engine for turn-based dungeon crawlers
5
5
  Keywords: basic-expert,bx,dungeon-crawler,game-engine,osr,rpg,srd,ttrpg
6
6
  Author: Marsh Macy
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "osrlib"
3
- version = "2.4.0"
3
+ version = "2.5.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
@@ -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,161 @@
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
+ Markdown doesn't treat anything inside code as a link, so brackets in code, like `inventory["purse"]["gp"]`, stay as
17
+ they are.
18
+ """
19
+
20
+ import ast
21
+ import inspect
22
+ import re
23
+ import sys
24
+ from enum import StrEnum
25
+ from functools import cache
26
+ from itertools import pairwise
27
+ from typing import Any
28
+
29
+ from pydantic import AliasChoices, BaseModel, GetJsonSchemaHandler
30
+ from pydantic.fields import FieldInfo
31
+ from pydantic.json_schema import JsonSchemaMode, JsonSchemaValue
32
+ from pydantic_core import CoreSchema
33
+
34
+ # A fenced code block or a span in two or more backticks.
35
+ _LITERAL = re.compile(r"(```.*?```|~~~.*?~~~|``.+?``)", re.DOTALL)
36
+
37
+ # A span in single backticks, or a cross-reference: a label in brackets, then a target in brackets. The label is text,
38
+ # code spans, or both, like [`MoveParty`][osrlib.crawl.commands.MoveParty], [the rejection code
39
+ # reference][rejection-codes], or [a `MoveParty` command][osrlib.crawl.commands.MoveParty]. The expression matches the
40
+ # span or the cross-reference that starts first, so it never reads brackets inside code as a cross-reference.
41
+ _SPAN_OR_REFERENCE = re.compile(r"(`[^`\n]+`)|\[((?:[^\[\]`]|`[^`\n]+`)+)\]\[[^\]\s]+\]")
42
+
43
+
44
+ def _plain(text: str) -> str:
45
+ """Return Markdown with each mkdocstrings cross-reference reduced to its label, and code left as it is."""
46
+ if "][" not in text:
47
+ return text
48
+ parts = _LITERAL.split(text)
49
+ parts[::2] = [_SPAN_OR_REFERENCE.sub(lambda match: match.group(1) or match.group(2), part) for part in parts[::2]]
50
+ return "".join(parts)
51
+
52
+
53
+ @cache
54
+ def _module_docstrings(module_name: str) -> dict[str, dict[str, str]]:
55
+ """Map the qualified name of each class in a module to the plain docstrings of the fields it declares.
56
+
57
+ For a module whose source can't be read, like one installed as bytecode alone, the mapping is empty. The cache lasts
58
+ as long as the process, so after `importlib.reload` reloads a module, its schemas still have the docstrings from
59
+ before the reload.
60
+ """
61
+ try:
62
+ tree = ast.parse(inspect.getsource(sys.modules[module_name]))
63
+ except KeyError, OSError, TypeError, SyntaxError:
64
+ return {}
65
+ classes: dict[str, dict[str, str]] = {}
66
+
67
+ def collect(body: list[ast.stmt], prefix: str) -> None:
68
+ for node in body:
69
+ if isinstance(node, ast.ClassDef):
70
+ classes[prefix + node.name] = {
71
+ statement.target.id: _plain(inspect.cleandoc(following.value.value))
72
+ for statement, following in pairwise(node.body)
73
+ if isinstance(statement, ast.AnnAssign)
74
+ and isinstance(statement.target, ast.Name)
75
+ and isinstance(following, ast.Expr)
76
+ and isinstance(following.value, ast.Constant)
77
+ and isinstance(following.value.value, str)
78
+ }
79
+ collect(node.body, f"{prefix}{node.name}.")
80
+
81
+ collect(tree.body, "")
82
+ return classes
83
+
84
+
85
+ def _field_docstrings(cls: type[BaseModel]) -> dict[str, str]:
86
+ """Return the plain docstring of each field, from the class or from the nearest ancestor that documents it."""
87
+ docstrings: dict[str, str] = {}
88
+ for ancestor in reversed(cls.__mro__):
89
+ if ancestor is not BaseModel and issubclass(ancestor, BaseModel):
90
+ docstrings.update(_module_docstrings(ancestor.__module__).get(ancestor.__qualname__, {}))
91
+ return docstrings
92
+
93
+
94
+ def _reduce(schema: dict[str, Any]) -> None:
95
+ """Reduce the cross-references in a schema's top-level `description`."""
96
+ if isinstance(description := schema.get("description"), str):
97
+ schema["description"] = _plain(description)
98
+
99
+
100
+ def _property_name(name: str, info: FieldInfo, mode: JsonSchemaMode) -> str:
101
+ """Return the name of a field's property in a schema that uses aliases, as pydantic chooses it.
102
+
103
+ The alias for the mode is a name, an `AliasPath`, or an `AliasChoices`. For an `AliasChoices`, pydantic uses the
104
+ first choice that's a path of one name, like `"flat"` in `AliasChoices(AliasPath("outer", "inner"), "flat")`. For
105
+ an `AliasPath` alone, even a path of one name, and for an `AliasChoices` with no such choice, it uses the field's
106
+ name.
107
+ """
108
+ alias = info.validation_alias if mode == "validation" else info.serialization_alias
109
+ if alias is None:
110
+ alias = info.alias
111
+ if isinstance(alias, str):
112
+ return alias
113
+ if isinstance(alias, AliasChoices):
114
+ for path in alias.convert_to_aliases():
115
+ if len(path) == 1 and isinstance(path[0], str):
116
+ return path[0]
117
+ return name
118
+
119
+
120
+ def _describe(cls: type[BaseModel], json_schema: JsonSchemaValue, handler: GetJsonSchemaHandler) -> None:
121
+ """Give a model's JSON Schema the docstring of each field, and reduce the cross-references in its descriptions.
122
+
123
+ A field declared with `Field(description=...)` has that description in the schema instead, with its cross-references
124
+ reduced. A property can be named for the field or for its alias, so the schema is described both when it uses
125
+ aliases and when it doesn't.
126
+
127
+ Args:
128
+ cls: The model.
129
+ json_schema: The model's JSON Schema, or a reference to it. `_describe` changes the schema in place.
130
+ handler: The handler pydantic passed to the model's `__get_pydantic_json_schema__`, which resolves a
131
+ reference to its definition.
132
+ """
133
+ schema = handler.resolve_ref_schema(json_schema)
134
+ _reduce(schema)
135
+ fields = {name: name for name in cls.model_fields}
136
+ # A property named for a field's alias belongs to that field, even when another field has the same name.
137
+ fields.update({_property_name(name, info, handler.mode): name for name, info in cls.model_fields.items()})
138
+ docstrings = _field_docstrings(cls)
139
+ properties: dict[str, Any] = schema.get("properties", {})
140
+ for key, prop in properties.items():
141
+ name = fields.get(key)
142
+ if name is not None and cls.model_fields[name].description is None and name in docstrings:
143
+ prop["description"] = docstrings[name]
144
+ else:
145
+ _reduce(prop)
146
+
147
+
148
+ class _StrEnum(StrEnum):
149
+ """The base class of every osrlib enum. It reduces the cross-references in the description of the enum's schema."""
150
+
151
+ @classmethod
152
+ def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler, /) -> JsonSchemaValue:
153
+ """Return the enum's JSON Schema, with each cross-reference in its description reduced to its label.
154
+
155
+ Pydantic calls this each time it builds the enum's schema, after it writes the enum's docstring as the
156
+ description. The call reads and changes only the enum's schema, so it doesn't depend on the order in which
157
+ pydantic builds the definitions of a larger schema.
158
+ """
159
+ json_schema = handler(schema)
160
+ _reduce(handler.resolve_ref_schema(json_schema))
161
+ return json_schema
@@ -63,10 +63,10 @@ assert (check.roll, check.success) == (18, False)
63
63
  ```
64
64
  """
65
65
 
66
- from enum import StrEnum
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(StrEnum):
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(StrEnum):
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(BaseModel):
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(BaseModel):
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(BaseModel):
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(BaseModel):
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(BaseModel):
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 dictionary isn't
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 enum import StrEnum
22
+ from osrlib.core._descriptions import _StrEnum
23
23
 
24
24
  __all__ = [
25
25
  "Alignment",
26
26
  ]
27
27
 
28
28
 
29
- class Alignment(StrEnum):
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