osrlib 2.7.0__tar.gz → 2.8.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.7.0 → osrlib-2.8.0}/PKG-INFO +1 -1
  2. {osrlib-2.7.0 → osrlib-2.8.0}/pyproject.toml +1 -1
  3. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/combat.py +6 -2
  4. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/events.py +5 -1
  5. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/items.py +271 -1
  6. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/spells.py +123 -41
  7. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_feature_handles.py +52 -0
  8. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_magic_items.py +25 -13
  9. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_party_members.py +41 -1
  10. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_spells.py +42 -10
  11. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/battle.py +91 -21
  12. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/commands.py +86 -30
  13. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/dungeon.py +40 -8
  14. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/events.py +14 -0
  15. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/session.py +56 -7
  16. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/views.py +464 -95
  17. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/equipment.json +174 -18
  18. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/magic_items.json +336 -2
  19. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/persistence.py +8 -1
  20. {osrlib-2.7.0 → osrlib-2.8.0}/LICENSE +0 -0
  21. {osrlib-2.7.0 → osrlib-2.8.0}/LICENSE-OGL.md +0 -0
  22. {osrlib-2.7.0 → osrlib-2.8.0}/README.md +0 -0
  23. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/__init__.py +0 -0
  24. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/__init__.py +0 -0
  25. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/_descriptions.py +0 -0
  26. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/abilities.py +0 -0
  27. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/alignment.py +0 -0
  28. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/character.py +0 -0
  29. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/classes.py +0 -0
  30. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/clock.py +0 -0
  31. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/creature.py +0 -0
  32. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/dice.py +0 -0
  33. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/effects.py +0 -0
  34. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/frozen.py +0 -0
  35. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/monsters.py +0 -0
  36. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/npc.py +0 -0
  37. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/rng.py +0 -0
  38. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/ruleset.py +0 -0
  39. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/tables.py +0 -0
  40. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/treasure.py +0 -0
  41. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/core/validation.py +0 -0
  42. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/__init__.py +0 -0
  43. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_arrival.py +0 -0
  44. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_doors.py +0 -0
  45. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_gating.py +0 -0
  46. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_hauling.py +0 -0
  47. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_items.py +0 -0
  48. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_light.py +0 -0
  49. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_movement.py +0 -0
  50. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_odometer.py +0 -0
  51. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_party_location.py +0 -0
  52. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_search.py +0 -0
  53. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_town.py +0 -0
  54. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/_treasure.py +0 -0
  55. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/adventure.py +0 -0
  56. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/content_pack.py +0 -0
  57. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/encounter.py +0 -0
  58. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/exploration.py +0 -0
  59. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/gates.py +0 -0
  60. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/interpreter.py +0 -0
  61. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/narrative.py +0 -0
  62. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/party.py +0 -0
  63. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/quests.py +0 -0
  64. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/stocking.py +0 -0
  65. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/crawl/triggers.py +0 -0
  66. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/LICENSE-OGL.md +0 -0
  67. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/__init__.py +0 -0
  68. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/abilities.json +0 -0
  69. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/classes.json +0 -0
  70. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/combat_tables.json +0 -0
  71. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/encounter_tables.json +0 -0
  72. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/languages.json +0 -0
  73. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/monsters.json +0 -0
  74. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/spells.json +0 -0
  75. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/data/treasure.json +0 -0
  76. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/errors.py +0 -0
  77. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/messages.py +0 -0
  78. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/py.typed +0 -0
  79. {osrlib-2.7.0 → osrlib-2.8.0}/src/osrlib/versioning.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: osrlib
3
- Version: 2.7.0
3
+ Version: 2.8.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.7.0"
3
+ version = "2.8.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
@@ -173,7 +173,9 @@ from osrlib.core.items import (
173
173
  MissileRanges,
174
174
  WeaponQuality,
175
175
  WeaponTemplate,
176
+ _masked_names,
176
177
  _shield_ac_parts,
178
+ _with_article,
177
179
  equipped_item_modifiers,
178
180
  magic_item_template,
179
181
  )
@@ -2099,7 +2101,8 @@ def destroy_equipment(
2099
2101
  items that save stay in the inventory's `items` list, no longer equipped. The saving
2100
2102
  throws report no events of their own. The function returns one
2101
2103
  [`EquipmentDestroyedEvent`][osrlib.core.events.EquipmentDestroyedEvent], which lists
2102
- the items destroyed and the items saved. In a
2104
+ the items destroyed and the items saved. It names an unidentified magic item by its masked
2105
+ name, like `"a sword with a faint aura"`, because the players see the event. In a
2103
2106
  [`GameSession`][osrlib.crawl.session.GameSession], that event's page says where a dead
2104
2107
  party member's saved items go.
2105
2108
 
@@ -2176,7 +2179,8 @@ def destroy_equipment(
2176
2179
  if save_stream.randbelow(20) + 1 + best_bonus >= required:
2177
2180
  saved.append(instance)
2178
2181
  continue
2179
- destroyed.append(template.name)
2182
+ # The event has player visibility, so an unidentified item is named as the inventory shows it.
2183
+ destroyed.append(template.name if instance.identified else _with_article(_masked_names(instance)[0]))
2180
2184
  else:
2181
2185
  destroyed.append(instance.template.name)
2182
2186
  inventory.items = list(saved)
@@ -849,7 +849,11 @@ class EquipmentDestroyedEvent(Event):
849
849
  """The entity id of the victim."""
850
850
 
851
851
  item_names: tuple[str, ...]
852
- """The display names of the items that were destroyed."""
852
+ """The names of the items that were destroyed, as the players know them: a mundane item's
853
+ `name`, like `"Torches (6)"`, an identified magic item's `name`, and an unidentified magic item's
854
+ masked name, like `"a sword with a faint aura"`, the `display` that
855
+ [`MemberView.inventory`][osrlib.crawl.views.MemberView.inventory] showed for it. The event has
856
+ player visibility, so it never names an unidentified item by its true name."""
853
857
 
854
858
  saved_items: tuple[str, ...] = ()
855
859
  """The instance ids of the magic items that passed their save and still exist. Empty when none survived,
@@ -88,10 +88,11 @@ print(torches.quantity, inventory.purse.gp, movement_rate_feet(inventory, Rulese
88
88
  ```
89
89
  """
90
90
 
91
+ import re
91
92
  from collections.abc import Mapping
92
93
  from typing import TYPE_CHECKING, Annotated, Any, Literal
93
94
 
94
- from pydantic import ConfigDict, Field, field_validator, model_validator
95
+ from pydantic import ConfigDict, Field, ValidationInfo, field_validator, model_validator
95
96
 
96
97
  import osrlib.core
97
98
  from osrlib.core._descriptions import _StrEnum
@@ -99,6 +100,7 @@ from osrlib.core.classes import ArmourPolicyKind, ClassDefinition, WeaponPolicyK
99
100
  from osrlib.core.dice import parse
100
101
  from osrlib.core.effects import ModifierSpec
101
102
  from osrlib.core.frozen import FrozenMap, _Model
103
+ from osrlib.core.monsters import _regular_plural
102
104
  from osrlib.core.rng import RngStream
103
105
  from osrlib.core.ruleset import EncumbranceMode, Ruleset
104
106
  from osrlib.core.treasure import MagicItemType, TreasureEntry
@@ -361,6 +363,42 @@ def _check_missile_ranges(qualities: tuple[WeaponQuality, ...], missile_ranges:
361
363
  raise ValueError("missile ranges are present exactly when the missile quality is")
362
364
 
363
365
 
366
+ _IRREGULAR_PLURALS = {"staff": "staves"}
367
+ """The plural of every word that names an item and doesn't take the regular English ending."""
368
+
369
+ _HEAD_NOUN_END = re.compile(r" (?i:of|with|vs) |, | [+-]\d| (?=[IVX]+$)| \(")
370
+ """Where the words that name an item end and the words that qualify it begin: `of`, `with`, or `vs` in any case, a
371
+ comma, a bonus like `+1`, a closing Roman numeral, or an opening parenthesis."""
372
+
373
+ _LAST_WORD = re.compile(r"(?P<words>.*?)(?P<noun>\S+)(?P<space>\s*)")
374
+ """The words before the last word, the last word, and any whitespace after it."""
375
+
376
+
377
+ def _item_plural(name: str) -> str:
378
+ """Return the plural of an item's display name, with the ending on the word that names the item.
379
+
380
+ That word is the last one before the first match of `_HEAD_NOUN_END`, or the last word of a name with no match, so
381
+ `"vial of holy water"` becomes `"vials of holy water"`, `"Staff Of Power"` becomes `"Staves Of Power"`, and
382
+ `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. It takes the ending of `_regular_plural`, unless
383
+ `_IRREGULAR_PLURALS` lists it, and keeps its capital, so `"Staff of the Magi"` becomes `"Staves of the Magi"`.
384
+ The ending goes straight on the word, and any whitespace after the word stays after the ending, so a name with
385
+ two spaces before its `of` keeps them after the ending. The SRD compiler writes the plural of every built-in
386
+ template with this function, and a template written without a plural gets it from this function too.
387
+ """
388
+ end = _HEAD_NOUN_END.search(name)
389
+ head, tail = (name[: end.start()], name[end.start() :]) if end else (name, "")
390
+ match = _LAST_WORD.fullmatch(head)
391
+ if match is None:
392
+ return name
393
+ noun = match["noun"]
394
+ irregular = _IRREGULAR_PLURALS.get(noun.lower())
395
+ if irregular is None:
396
+ noun = _regular_plural(noun)
397
+ else:
398
+ noun = irregular.capitalize() if noun[:1].isupper() else irregular
399
+ return match["words"] + noun + match["space"] + tail
400
+
401
+
364
402
  class WeaponTemplate(_Model):
365
403
  """A mundane weapon, from the SRD's weapon table.
366
404
 
@@ -383,6 +421,29 @@ class WeaponTemplate(_Model):
383
421
  """
384
422
  name: str
385
423
  """The display name, for example `"Sword"`."""
424
+ display_name: str = Field(default="", validate_default=True)
425
+ """What to call one of these weapons in a sentence, like `"sword"` or `"two-handed sword"`.
426
+
427
+ It's lowercase unless a word is a proper noun or an abbreviation, and it has no article, so put a number or an
428
+ article in front of it: "a sword", "2 swords".
429
+ [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names] gives it to the players' client.
430
+
431
+ A template you write that leaves it out gets its `name`.
432
+ """
433
+ display_name_plural: str = Field(default="", validate_default=True)
434
+ """What to call two or more of these weapons, like `"swords"` or `"staves"`.
435
+
436
+ [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] gives it to the players' client. A
437
+ template you write that leaves it out gets `display_name` with the regular English ending on the word that names the
438
+ item: the last word before the first `of`, `with`, or `vs`, a comma, a bonus like `+1`, a closing Roman numeral, or
439
+ an opening parenthesis, or the last word when the name has none of them. So `"Idol of the drowned saint"` becomes
440
+ `"Idols of the drowned saint"`, and `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. The ending is `s`, or `es`
441
+ after `s`, `x`, `z`, `ch`, or `sh`, or `ies` in place of a `y` that follows a consonant, and `staff` becomes
442
+ `staves` with its capital kept, so `"Staff of the Magi"` becomes `"Staves of the Magi"`. The connecting words count
443
+ in any case, so `"Staff Of Power"` becomes `"Staves Of Power"`, and any spaces after the word stay after the ending.
444
+ The compiled plural of every built-in template follows the same rule. Set it yourself when the name is already
445
+ plural, like `"Torches (6)"`, or when the plural is irregular.
446
+ """
386
447
  cost_gp: int = Field(ge=0)
387
448
  """The listed price in gold pieces, for one weapon."""
388
449
  weight_coins: int = Field(ge=0)
@@ -404,6 +465,16 @@ class WeaponTemplate(_Model):
404
465
  osrlib doesn't read it during play.
405
466
  """
406
467
 
468
+ @field_validator("display_name")
469
+ @classmethod
470
+ def _display_name_defaults_to_name(cls, value: str, info: ValidationInfo) -> str:
471
+ return value or info.data.get("name", "")
472
+
473
+ @field_validator("display_name_plural")
474
+ @classmethod
475
+ def _plural_defaults_to_regular_ending(cls, value: str, info: ValidationInfo) -> str:
476
+ return value or _item_plural(info.data.get("display_name", ""))
477
+
407
478
  @field_validator("damage")
408
479
  @classmethod
409
480
  def _damage_must_parse(cls, value: str) -> str:
@@ -445,6 +516,29 @@ class ArmourTemplate(_Model):
445
516
  index](https://mmacy.github.io/osrlib-python/reference/content-ids/equipment/)."""
446
517
  name: str
447
518
  """The display name."""
519
+ display_name: str = Field(default="", validate_default=True)
520
+ """What to call one of these in a sentence, like `"shield"` or `"suit of chainmail"`.
521
+
522
+ Body armour is named as a suit, so a count reads "2 suits of chainmail". It's lowercase unless a
523
+ word is a proper noun or an abbreviation, and it has no article, so put a number or an article in
524
+ front of it. [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names] gives it to the players' client.
525
+
526
+ A template you write that leaves it out gets its `name`.
527
+ """
528
+ display_name_plural: str = Field(default="", validate_default=True)
529
+ """What to call two or more of these, like `"shields"` or `"suits of chainmail"`.
530
+
531
+ [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] gives it to the players' client. A
532
+ template you write that leaves it out gets `display_name` with the regular English ending on the word that names the
533
+ item: the last word before the first `of`, `with`, or `vs`, a comma, a bonus like `+1`, a closing Roman numeral, or
534
+ an opening parenthesis, or the last word when the name has none of them. So `"Idol of the drowned saint"` becomes
535
+ `"Idols of the drowned saint"`, and `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. The ending is `s`, or `es`
536
+ after `s`, `x`, `z`, `ch`, or `sh`, or `ies` in place of a `y` that follows a consonant, and `staff` becomes
537
+ `staves` with its capital kept, so `"Staff of the Magi"` becomes `"Staves of the Magi"`. The connecting words count
538
+ in any case, so `"Staff Of Power"` becomes `"Staves Of Power"`, and any spaces after the word stay after the ending.
539
+ The compiled plural of every built-in template follows the same rule. Set it yourself when the name is already
540
+ plural, like `"Torches (6)"`, or when the plural is irregular.
541
+ """
448
542
  cost_gp: int = Field(ge=0)
449
543
  """The listed price in gold pieces."""
450
544
  weight_coins: int = Field(ge=0)
@@ -466,6 +560,16 @@ class ArmourTemplate(_Model):
466
560
  osrlib doesn't read it during play.
467
561
  """
468
562
 
563
+ @field_validator("display_name")
564
+ @classmethod
565
+ def _display_name_defaults_to_name(cls, value: str, info: ValidationInfo) -> str:
566
+ return value or info.data.get("name", "")
567
+
568
+ @field_validator("display_name_plural")
569
+ @classmethod
570
+ def _plural_defaults_to_regular_ending(cls, value: str, info: ValidationInfo) -> str:
571
+ return value or _item_plural(info.data.get("display_name", ""))
572
+
469
573
  @model_validator(mode="after")
470
574
  def _body_armour_or_shield(self) -> ArmourTemplate:
471
575
  body_fields = (self.ac is not None, self.ac_ascending is not None, self.category is not None)
@@ -553,6 +657,32 @@ class GearTemplate(_Model):
553
657
  """The display name as the price list prints it, which includes the lot size for gear sold in lots:
554
658
  `"Torches (6)"`, `"Iron spikes (12)"`.
555
659
  """
660
+ display_name: str = Field(default="", validate_default=True)
661
+ """What to call one unit of this gear in a sentence, like `"torch"` or `"vial of holy water"`.
662
+
663
+ It names one of the units that [`ItemInstance.quantity`][osrlib.core.items.ItemInstance.quantity]
664
+ counts, not a lot from the price list, so `"Torches (6)"` is `"torch"`, and a stack of six reads
665
+ "6 torches". Where the price list names a substance, it names the container or the measure the
666
+ session counts: `"vial of holy water"`, `"flask of oil"`, `"pint of wine"`. It's lowercase unless a
667
+ word is a proper noun or an abbreviation, and it has no article, so put a number or an article in
668
+ front of it. [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names] gives it to the players' client.
669
+
670
+ A template you write that leaves it out gets its `name`.
671
+ """
672
+ display_name_plural: str = Field(default="", validate_default=True)
673
+ """What to call two or more units, like `"torches"` or `"vials of holy water"`.
674
+
675
+ [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] gives it to the players' client. A
676
+ template you write that leaves it out gets `display_name` with the regular English ending on the word that names the
677
+ item: the last word before the first `of`, `with`, or `vs`, a comma, a bonus like `+1`, a closing Roman numeral, or
678
+ an opening parenthesis, or the last word when the name has none of them. So `"Idol of the drowned saint"` becomes
679
+ `"Idols of the drowned saint"`, and `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. The ending is `s`, or `es`
680
+ after `s`, `x`, `z`, `ch`, or `sh`, or `ies` in place of a `y` that follows a consonant, and `staff` becomes
681
+ `staves` with its capital kept, so `"Staff of the Magi"` becomes `"Staves of the Magi"`. The connecting words count
682
+ in any case, so `"Staff Of Power"` becomes `"Staves Of Power"`, and any spaces after the word stay after the ending.
683
+ The compiled plural of every built-in template follows the same rule. Set it yourself when the name is already
684
+ plural, like `"Torches (6)"`, or when the plural is irregular.
685
+ """
556
686
  cost_gp: int = Field(ge=0)
557
687
  """The listed price in gold pieces, for one lot."""
558
688
  lot_size: int = Field(default=1, ge=1)
@@ -576,6 +706,16 @@ class GearTemplate(_Model):
576
706
  osrlib doesn't read it during play.
577
707
  """
578
708
 
709
+ @field_validator("display_name")
710
+ @classmethod
711
+ def _display_name_defaults_to_name(cls, value: str, info: ValidationInfo) -> str:
712
+ return value or info.data.get("name", "")
713
+
714
+ @field_validator("display_name_plural")
715
+ @classmethod
716
+ def _plural_defaults_to_regular_ending(cls, value: str, info: ValidationInfo) -> str:
717
+ return value or _item_plural(info.data.get("display_name", ""))
718
+
579
719
 
580
720
  class AmmunitionTemplate(_Model):
581
721
  """Ammunition for a missile weapon: arrows, quarrels, sling stones.
@@ -596,6 +736,30 @@ class AmmunitionTemplate(_Model):
596
736
  [the equipment id index](https://mmacy.github.io/osrlib-python/reference/content-ids/equipment/)."""
597
737
  name: str
598
738
  """The display name as the price list prints it, which includes the lot: `"Arrows (quiver of 20)"`."""
739
+ display_name: str = Field(default="", validate_default=True)
740
+ """What to call one unit of this ammunition in a sentence, like `"arrow"` or `"crossbow bolt"`.
741
+
742
+ It names one of the units that [`ItemInstance.quantity`][osrlib.core.items.ItemInstance.quantity]
743
+ counts, not the lot, so `"Arrows (quiver of 20)"` is `"arrow"`, and a full quiver reads "20 arrows".
744
+ It's lowercase unless a word is a proper noun or an abbreviation, and it has no article.
745
+ [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names] gives it to the players' client.
746
+
747
+ A template you write that leaves it out gets its `name`.
748
+ """
749
+ display_name_plural: str = Field(default="", validate_default=True)
750
+ """What to call two or more units, like `"arrows"` or `"crossbow bolts"`.
751
+
752
+ [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] gives it to the players' client. A
753
+ template you write that leaves it out gets `display_name` with the regular English ending on the word that names the
754
+ item: the last word before the first `of`, `with`, or `vs`, a comma, a bonus like `+1`, a closing Roman numeral, or
755
+ an opening parenthesis, or the last word when the name has none of them. So `"Idol of the drowned saint"` becomes
756
+ `"Idols of the drowned saint"`, and `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. The ending is `s`, or `es`
757
+ after `s`, `x`, `z`, `ch`, or `sh`, or `ies` in place of a `y` that follows a consonant, and `staff` becomes
758
+ `staves` with its capital kept, so `"Staff of the Magi"` becomes `"Staves of the Magi"`. The connecting words count
759
+ in any case, so `"Staff Of Power"` becomes `"Staves Of Power"`, and any spaces after the word stay after the ending.
760
+ The compiled plural of every built-in template follows the same rule. Set it yourself when the name is already
761
+ plural, like `"Torches (6)"`, or when the plural is irregular.
762
+ """
599
763
  cost_gp: int = Field(ge=0)
600
764
  """The listed price in gold pieces, for one lot. 0 for sling stones."""
601
765
  lot_size: int = Field(default=1, ge=1)
@@ -613,6 +777,16 @@ class AmmunitionTemplate(_Model):
613
777
  osrlib doesn't read it during play.
614
778
  """
615
779
 
780
+ @field_validator("display_name")
781
+ @classmethod
782
+ def _display_name_defaults_to_name(cls, value: str, info: ValidationInfo) -> str:
783
+ return value or info.data.get("name", "")
784
+
785
+ @field_validator("display_name_plural")
786
+ @classmethod
787
+ def _plural_defaults_to_regular_ending(cls, value: str, info: ValidationInfo) -> str:
788
+ return value or _item_plural(info.data.get("display_name", ""))
789
+
616
790
 
617
791
  ItemTemplate = Annotated[
618
792
  WeaponTemplate | ArmourTemplate | GearTemplate | AmmunitionTemplate,
@@ -957,6 +1131,36 @@ class MagicItemTemplate(_Model):
957
1131
  index](https://mmacy.github.io/osrlib-python/reference/content-ids/magic-items/)."""
958
1132
  name: str
959
1133
  """The display name. Show this only once the instance is identified."""
1134
+ display_name: str = Field(default="", validate_default=True)
1135
+ """What to call one of these items in a sentence once the party knows what it is, like
1136
+ `"potion of healing"` or `"sword +1"`.
1137
+
1138
+ It's lowercase unless a word is a proper noun or an abbreviation, like the `ESP` of
1139
+ `"potion of ESP"`, and it has no article, so put a number or an article in front of it. For
1140
+ enchanted ammunition it names one of the units that
1141
+ [`MagicItemInstance.quantity`][osrlib.core.items.MagicItemInstance.quantity] counts, so
1142
+ `"Arrows +1 (3d10 arrows)"` is `"arrow +1"`. Footwear and gloves are named as a pair, like
1143
+ `"pair of boots of speed"`, so a count reads "2 pairs of boots of speed".
1144
+
1145
+ Like `name`, show it only once the instance is identified. Until then,
1146
+ [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names] names the item by its masked name.
1147
+
1148
+ A template you construct yourself that leaves it out gets its `name`.
1149
+ """
1150
+ display_name_plural: str = Field(default="", validate_default=True)
1151
+ """What to call two or more of these items, like `"potions of healing"` or `"swords +1"`.
1152
+
1153
+ [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] gives it to the players' client. A
1154
+ template you construct yourself that leaves it out gets `display_name` with the regular English ending on the word
1155
+ that names the item: the last word before the first `of`, `with`, or `vs`, a comma, a bonus like `+1`, a closing
1156
+ Roman numeral, or an opening parenthesis, or the last word when the name has none of them. So `"Idol of the drowned
1157
+ saint"` becomes `"Idols of the drowned saint"`, and `"Lantern (hooded)"` becomes `"Lanterns (hooded)"`. The ending
1158
+ is `s`, or `es` after `s`, `x`, `z`, `ch`, or `sh`, or `ies` in place of a `y` that follows a consonant, and `staff`
1159
+ becomes `staves` with its capital kept, so `"Staff of the Magi"` becomes `"Staves of the Magi"`. The connecting
1160
+ words count in any case, so `"Staff Of Power"` becomes `"Staves Of Power"`, and any spaces after the word stay after
1161
+ the ending. The compiled plural of every built-in template follows the same rule. Set it yourself when the name is
1162
+ already plural, like `"Torches (6)"`, or when the plural is irregular.
1163
+ """
960
1164
  category: MagicItemCategory
961
1165
  """What kind of item it is. See [`MagicItemCategory`][osrlib.core.items.MagicItemCategory]."""
962
1166
  base_item_id: str | None = None
@@ -1027,6 +1231,16 @@ class MagicItemTemplate(_Model):
1027
1231
  osrlib doesn't read it during play.
1028
1232
  """
1029
1233
 
1234
+ @field_validator("display_name")
1235
+ @classmethod
1236
+ def _display_name_defaults_to_name(cls, value: str, info: ValidationInfo) -> str:
1237
+ return value or info.data.get("name", "")
1238
+
1239
+ @field_validator("display_name_plural")
1240
+ @classmethod
1241
+ def _plural_defaults_to_regular_ending(cls, value: str, info: ValidationInfo) -> str:
1242
+ return value or _item_plural(info.data.get("display_name", ""))
1243
+
1030
1244
  @field_validator("charges_dice", "quantity_dice")
1031
1245
  @classmethod
1032
1246
  def _dice_must_parse(cls, value: str | None) -> str | None:
@@ -1783,6 +1997,16 @@ class ItemInstance(_Model):
1783
1997
  """The item itself, one of the four equipment templates. See [`ItemTemplate`][osrlib.core.items.ItemTemplate]. The
1784
1998
  whole template is embedded rather than referenced by id, so an instance of an item an adventure bundled stays
1785
1999
  readable without that adventure.
2000
+
2001
+ A session gives an embedded template the display names of the template its catalog,
2002
+ [`GameSession.effective_equipment`][osrlib.crawl.session.GameSession.effective_equipment], has under the same id.
2003
+ It does this to every stack a party member or an NPC adventurer carries when the session starts, when
2004
+ [`load_game`][osrlib.persistence.load_game] restores it, and when [`AddMember`][osrlib.crawl.commands.AddMember]
2005
+ adds a member. Only `display_name` and `display_name_plural` change, with the entries of `overrides_applied` that
2006
+ name those two fields, which record where the names came from. The rest of the template is rules data that travels
2007
+ with the character. So a stack from a save or a party document that osrlib 2.7.0 wrote, whose
2008
+ template has no display names, is named as the catalog names it, in the views and in the next save. A template
2009
+ whose id the catalog doesn't have, like an item another adventure bundled, keeps the names it has.
1786
2010
  """
1787
2011
  quantity: int = Field(default=1, ge=1)
1788
2012
  """How many units the stack contains, counting individual items rather than lots: buying one lot of torches gives
@@ -2275,6 +2499,52 @@ def magic_item_template(instance: MagicItemInstance) -> MagicItemTemplate:
2275
2499
  return load_magic_items().get(instance.template_id)
2276
2500
 
2277
2501
 
2502
+ _MASKED_CATEGORY_NAMES = {
2503
+ MagicItemCategory.POTION: ("potion", "potions"),
2504
+ MagicItemCategory.SCROLL: ("scroll", "scrolls"),
2505
+ MagicItemCategory.RING: ("ring", "rings"),
2506
+ MagicItemCategory.WAND: ("wand", "wands"),
2507
+ MagicItemCategory.STAFF: ("staff", "staves"),
2508
+ MagicItemCategory.ROD: ("rod", "rods"),
2509
+ MagicItemCategory.MISC: ("curious device", "curious devices"),
2510
+ }
2511
+ """What the players call an unidentified item of each category that isn't an enchanted arm."""
2512
+
2513
+
2514
+ def _masked_names(instance: MagicItemInstance) -> tuple[str, str]:
2515
+ """Return what the players call an unidentified magic item, for one and for two or more, with no article.
2516
+
2517
+ An item whose category has a name in `_MASKED_CATEGORY_NAMES` gets that name, like `"potion"`. An enchanted
2518
+ weapon, piece of ammunition, suit of armour, or shield is named after one unit of the mundane item underneath it,
2519
+ its `display_name` followed by "with a faint aura", the concession made because *detect magic* exists: `"arrow
2520
+ with a faint aura"`, `"suit of chainmail with a faint aura"`. A suit of enchanted armour with no mundane item
2521
+ recorded is `"suit of armour with a faint aura"`.
2522
+
2523
+ The name depends on the category and the base alone, so a cursed item has the names of the item it passes for,
2524
+ and neither the bonus nor the curse shows.
2525
+ """
2526
+ from osrlib.data import load_equipment
2527
+
2528
+ template = magic_item_template(instance)
2529
+ category_names = _MASKED_CATEGORY_NAMES.get(template.category)
2530
+ if category_names is not None:
2531
+ return category_names
2532
+ base_id = instance.base_item_id or template.base_item_id
2533
+ if base_id is not None:
2534
+ base = load_equipment().get(base_id)
2535
+ singular, plural = base.display_name, base.display_name_plural
2536
+ elif template.category is MagicItemCategory.ARMOUR:
2537
+ singular, plural = "suit of armour", "suits of armour"
2538
+ else:
2539
+ singular, plural = "weapon", "weapons"
2540
+ return f"{singular} with a faint aura", f"{plural} with a faint aura"
2541
+
2542
+
2543
+ def _with_article(name: str) -> str:
2544
+ """Return `name` after the indefinite article, `"an"` before a vowel and `"a"` otherwise."""
2545
+ return f"{'an' if name[:1].lower() in ('a', 'e', 'i', 'o', 'u') else 'a'} {name}"
2546
+
2547
+
2278
2548
  def _shield_ac_parts(shield: AnyInstance | None, *, ascending: bool) -> tuple[int | None, int]:
2279
2549
  """Return the armour class a shield sets, or None, and the bonus the shield adds to armour class.
2280
2550
 
@@ -1395,30 +1395,14 @@ def memorize_spells(
1395
1395
  except ValueError:
1396
1396
  rejections.append(Rejection(code="magic.memorize.unknown_spell", params={"spell": selection.spell_id}))
1397
1397
  continue
1398
- if template.spell_list != profile.spell_list:
1399
- rejections.append(
1400
- Rejection(
1401
- code="magic.memorize.wrong_list",
1402
- params={"spell": selection.spell_id, "list": template.spell_list},
1403
- )
1404
- )
1398
+ rejection = _selection_rejection(caster, profile, template, selection)
1399
+ if rejection is not None:
1400
+ rejections.append(rejection)
1405
1401
  continue
1406
- if profile.kind == "divine" and selection.reversed:
1407
- rejections.append(
1408
- Rejection(code="magic.memorize.divine_reverses_at_cast", params={"spell": selection.spell_id})
1409
- )
1410
- continue
1411
- if profile.kind == "arcane":
1412
- if selection.spell_id not in getattr(caster, "spell_book", ()):
1413
- rejections.append(Rejection(code="magic.memorize.not_in_book", params={"spell": selection.spell_id}))
1414
- continue
1415
- if selection.reversed and template.reversed_form is None:
1416
- rejections.append(Rejection(code="magic.memorize.not_reversible", params={"spell": selection.spell_id}))
1417
- continue
1418
1402
  counts[template.level] = counts.get(template.level, 0) + 1
1419
1403
  slots = definition.row(caster.level).spell_slots
1420
1404
  for spell_level, count in sorted(counts.items()):
1421
- allowed = slots[spell_level - 1] if spell_level <= len(slots) else 0
1405
+ allowed = _slot_count(slots, spell_level)
1422
1406
  if count > allowed:
1423
1407
  rejections.append(
1424
1408
  Rejection(
@@ -1436,6 +1420,57 @@ def memorize_spells(
1436
1420
  return MemorizationResult(events=(event,))
1437
1421
 
1438
1422
 
1423
+ def _slot_count(slots: Sequence[int], spell_level: int) -> int:
1424
+ """Return a progression row's slot count at a spell level, which is 0 past the end of the row."""
1425
+ return slots[spell_level - 1] if spell_level <= len(slots) else 0
1426
+
1427
+
1428
+ def _selection_rejection(
1429
+ caster: Caster, profile: CasterProfile, template: SpellTemplate, selection: MemorizedSpell
1430
+ ) -> Rejection | None:
1431
+ """Return why `memorize_spells` refuses one copy for its spell and its form, or None when it doesn't.
1432
+
1433
+ These are the checks of a single copy against the caster, once the spell is known to be in the catalog. The
1434
+ slot counts are checked over the whole selection, with `_slot_count`.
1435
+ """
1436
+ if template.spell_list != profile.spell_list:
1437
+ return Rejection(
1438
+ code="magic.memorize.wrong_list", params={"spell": selection.spell_id, "list": template.spell_list}
1439
+ )
1440
+ if profile.kind == "divine" and selection.reversed:
1441
+ return Rejection(code="magic.memorize.divine_reverses_at_cast", params={"spell": selection.spell_id})
1442
+ if profile.kind == "arcane":
1443
+ if selection.spell_id not in getattr(caster, "spell_book", ()):
1444
+ return Rejection(code="magic.memorize.not_in_book", params={"spell": selection.spell_id})
1445
+ if selection.reversed and template.reversed_form is None:
1446
+ return Rejection(code="magic.memorize.not_reversible", params={"spell": selection.spell_id})
1447
+ return None
1448
+
1449
+
1450
+ def _preparable_spell_ids(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> tuple[str, ...]:
1451
+ """Return the ids of the spells `memorize_spells` accepts one normal-form copy of, in the catalog's order.
1452
+
1453
+ A spell is here exactly when that one-copy selection gets none of the rejections that belong to the spell and
1454
+ the caster: `not_a_caster`, `unknown_spell`, `wrong_list`, `not_in_book`, and `slots_exceeded`. Every spell in
1455
+ the catalog is known, and one copy exceeds the slots at its level only when there are none.
1456
+ """
1457
+ profile = caster_profile(definition)
1458
+ if profile is None:
1459
+ return ()
1460
+ slots = definition.row(caster.level).spell_slots
1461
+ book = set(getattr(caster, "spell_book", ())) if profile.kind == "arcane" else None
1462
+ return tuple(
1463
+ template.id
1464
+ for template in catalog.spells
1465
+ # The first three tests skip only spells that the checks after them refuse, and they cost less than the
1466
+ # MemorizedSpell and Rejection models those checks build. `_selection_rejection` decides every spell left.
1467
+ if template.spell_list == profile.spell_list
1468
+ and (book is None or template.id in book)
1469
+ and _slot_count(slots, template.level) > 0
1470
+ and _selection_rejection(caster, profile, template, MemorizedSpell(spell_id=template.id)) is None
1471
+ )
1472
+
1473
+
1439
1474
  class SpellBookResult(_Model):
1440
1475
  """What came of a call to [`add_spell_to_book`][osrlib.core.spells.add_spell_to_book].
1441
1476
 
@@ -1615,35 +1650,82 @@ def add_spell_to_book(
1615
1650
  assert [rejection.code for rejection in refused.rejections] == ["magic.book.wrong_list"]
1616
1651
  ```
1617
1652
  """
1653
+ rejection = _book_rejection(caster, definition, catalog, spell_id)
1654
+ if rejection is not None:
1655
+ return SpellBookResult(rejections=(rejection,))
1656
+ caster.spell_book = (*caster.spell_book, spell_id)
1657
+ return SpellBookResult(events=(SpellBookUpdatedEvent(caster_id=_entity_id(caster), spell_id=spell_id),))
1658
+
1659
+
1660
+ def _book_rejection(
1661
+ caster: Caster, definition: ClassDefinition, catalog: SpellCatalog, spell_id: str
1662
+ ) -> Rejection | None:
1663
+ """Return why `add_spell_to_book` refuses a spell, or None when it accepts it.
1664
+
1665
+ The checks run in a fixed order and stop at the first that fails. This function makes the checks of the class
1666
+ and of the spell's id, and `_book_template_rejection` makes the rest.
1667
+ """
1618
1668
  profile = caster_profile(definition)
1619
1669
  if profile is None or profile.kind != "arcane":
1620
- return SpellBookResult(rejections=(Rejection(code="magic.book.not_arcane", params={"class": definition.id}),))
1670
+ return Rejection(code="magic.book.not_arcane", params={"class": definition.id})
1621
1671
  try:
1622
1672
  template = catalog.get(spell_id)
1623
1673
  except ValueError:
1624
- return SpellBookResult(rejections=(Rejection(code="magic.book.unknown_spell", params={"spell": spell_id}),))
1674
+ return Rejection(code="magic.book.unknown_spell", params={"spell": spell_id})
1675
+ return _book_template_rejection(caster, definition, catalog, profile, template)
1676
+
1677
+
1678
+ def _book_template_rejection(
1679
+ caster: Caster,
1680
+ definition: ClassDefinition,
1681
+ catalog: SpellCatalog,
1682
+ profile: CasterProfile,
1683
+ template: SpellTemplate,
1684
+ *,
1685
+ open_slots: tuple[int, ...] | None = None,
1686
+ ) -> Rejection | None:
1687
+ """Return why `add_spell_to_book` refuses a spell of the catalog for an arcane caster, or None when it accepts it.
1688
+
1689
+ `profile` is the caster's arcane profile, and `template` is the spell from `catalog`. `open_slots` is the
1690
+ caster's `open_book_capacity`, which a caller checking many spells against one book passes so that it's computed
1691
+ once. Without it, the capacity is computed only for a spell that passes every earlier check.
1692
+ """
1625
1693
  if template.spell_list != profile.spell_list:
1626
- return SpellBookResult(
1627
- rejections=(
1628
- Rejection(code="magic.book.wrong_list", params={"spell": spell_id, "list": template.spell_list}),
1629
- )
1694
+ return Rejection(code="magic.book.wrong_list", params={"spell": template.id, "list": template.spell_list})
1695
+ if template.id in caster.spell_book:
1696
+ return Rejection(code="magic.book.duplicate", params={"spell": template.id})
1697
+ if open_slots is None:
1698
+ open_slots = open_book_capacity(caster, definition, catalog)
1699
+ if _slot_count(open_slots, template.level) == 0:
1700
+ capacity = _slot_count(definition.row(caster.level).spell_slots, template.level)
1701
+ return Rejection(
1702
+ code="magic.book.capacity_exceeded",
1703
+ params={"spell": template.id, "spell_level": template.level, "capacity": capacity},
1630
1704
  )
1631
- if spell_id in caster.spell_book:
1632
- return SpellBookResult(rejections=(Rejection(code="magic.book.duplicate", params={"spell": spell_id}),))
1705
+ return None
1706
+
1707
+
1708
+ def _learnable_spell_ids(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> tuple[str, ...]:
1709
+ """Return the ids of the spells `add_spell_to_book` accepts, in the catalog's order.
1710
+
1711
+ It's empty for a class with no spell book. Like `open_book_capacity`, it raises `ValueError` when the book has a
1712
+ spell that isn't in `catalog`.
1713
+ """
1714
+ profile = caster_profile(definition)
1715
+ if profile is None or profile.kind != "arcane":
1716
+ return ()
1633
1717
  open_slots = open_book_capacity(caster, definition, catalog)
1634
- if template.level > len(open_slots) or open_slots[template.level - 1] == 0:
1635
- slots = definition.row(caster.level).spell_slots
1636
- capacity = slots[template.level - 1] if template.level <= len(slots) else 0
1637
- return SpellBookResult(
1638
- rejections=(
1639
- Rejection(
1640
- code="magic.book.capacity_exceeded",
1641
- params={"spell": spell_id, "spell_level": template.level, "capacity": capacity},
1642
- ),
1643
- )
1644
- )
1645
- caster.spell_book = (*caster.spell_book, spell_id)
1646
- return SpellBookResult(events=(SpellBookUpdatedEvent(caster_id=_entity_id(caster), spell_id=spell_id),))
1718
+ book = set(caster.spell_book)
1719
+ return tuple(
1720
+ template.id
1721
+ for template in catalog.spells
1722
+ # The first three tests skip only spells that `_book_template_rejection` refuses, without building the
1723
+ # Rejection model. It decides every spell left.
1724
+ if template.spell_list == profile.spell_list
1725
+ and template.id not in book
1726
+ and _slot_count(open_slots, template.level) > 0
1727
+ and _book_template_rejection(caster, definition, catalog, profile, template, open_slots=open_slots) is None
1728
+ )
1647
1729
 
1648
1730
 
1649
1731
  def forget_excess_memorized(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> list[Event]: