diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ccfa33..d60b25c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - [`PileView.contents`][osrlib.crawl.views.PileView.contents] gives each thing in a pile as a [`PileItemView`][osrlib.crawl.views.PileItemView], with the id that the events use for it and its count, in the order of `items` (#316). A client reads `"holy_water"` and 2 there where `items` has `"holy_water×2"`. `items` doesn't change. - [`ItemIdentifiedEvent`][osrlib.crawl.events.ItemIdentifiedEvent] has two new fields, `display_name` and `display_name_plural`, the identified item's display names, like `"potion of healing"` (#316). A potion drunk before the party knew what it was is identified and used up in one command, so no view contains its name, but the event does. An event recorded before this release has empty names. Every field this release adds has a default, so a 2.7.0 save, view, or event still parses, and [`SCHEMA_VERSION`][osrlib.versioning.SCHEMA_VERSION] stays 4. - The gear in a save or a party document that osrlib 2.7.0 wrote takes the display names of the session's catalog (#316). Its embedded templates have no display names, so they validate with the defaults from the price-list `name`, like `"Holy water (vial)"`. When a session starts, when [`load_game`][osrlib.persistence.load_game] restores one, and when [`AddMember`][osrlib.crawl.commands.AddMember] adds a member, each template that a party member's or an NPC adventurer's stack embeds takes the `display_name` and `display_name_plural` of the catalog's template with the same id, with the `overrides_applied` entries that name those two fields. So holy water from a 2.7.0 save reads `"vial of holy water"` in `MemberView.inventory`, in the referee view, and in [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names], and the next save writes those names. Nothing else in the template changes, a template whose id the catalog lacks keeps its names, `AddMember`'s logged character keeps the templates it arrived with, and loading a save draws nothing. +- [`MemberView.preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells] and [`MemberView.learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] list the spells a member may select in a [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells] and write into their spell book with [`LearnSpell`][osrlib.crawl.commands.LearnSpell], in the order of [`GameSession.effective_spells`][osrlib.crawl.session.GameSession.effective_spells] (#326). The view and the commands make the same checks. A spell is in `preparable_spells` exactly when a `PrepareSpells` that selects one copy of it in its normal form is accepted, or is refused only for the moment and with none of `magic.memorize.not_a_caster`, `magic.memorize.unknown_spell`, `magic.memorize.wrong_list`, `magic.memorize.not_in_book`, and `magic.memorize.slots_exceeded`. An arcane caster may also prepare the reverse of a listed spell that `reversed_spell_names` names. A spell is in `learnable_spells` exactly when a `LearnSpell` for it is accepted, or is refused only for the moment and with none of `magic.book.not_arcane`, `magic.book.unknown_spell`, `magic.book.wrong_list`, `magic.book.duplicate`, and `magic.book.capacity_exceeded`. A selection made only of listed spells is still refused when it has more copies at a spell level than the member has slots there. A divine caster's `preparable_spells` has every spell on the class's list at the spell levels where the caster has a slot, including the spells the adventure bundles for that list. An arcane caster's `learnable_spells` has the spells on the list that aren't in the book, at the spell levels where the book has room. Neither list depends on the moment, so each is the same before the party has slept, during an encounter or a battle, and while the member can't act, although the session refuses the commands then. Before, the view named a spell only once a member had it, so a player couldn't find out that the adventure adds a spell their cleric may prepare or their magic-user may learn. +- [`MemberView.spell_slots`][osrlib.crawl.views.MemberView.spell_slots] is how many spells the member can memorize at each spell level, from the class's progression row for the member's level, so it's right for a custom class too, and [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels] is the level of each spell in `spell_names` (#326). With them, a client groups a prepare or learn dialog by spell level and fits it to the slots. `spell_names`, `reversed_spell_names`, and `spell_levels` name every spell in the two lists, and a spell that the members can't choose stays hidden, such as one the adventure bundles for a list that the party's classes don't cast from. The session works the four new fields out from the characters and the catalog, so a 2.7.0 save loads with them filled in. Every new field has a default, so a 2.7.0 player view still parses, and [`SCHEMA_VERSION`][osrlib.versioning.SCHEMA_VERSION] stays 4. ### Fixed @@ -705,7 +707,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - The documentation site: quickstart, guides, front-end walk-throughs, and a full reference for every command, event, rejection code, message code, RNG stream, and content id. - The typed surface: complete type hints under `py.typed`, checked in CI. -[Unreleased]: https://github.com/mmacy/osrlib-python/compare/v2.5.1...HEAD +[Unreleased]: https://github.com/mmacy/osrlib-python/compare/v2.7.0...HEAD +[2.7.0]: https://github.com/mmacy/osrlib-python/compare/v2.6.0...v2.7.0 +[2.6.0]: https://github.com/mmacy/osrlib-python/compare/v2.5.1...v2.6.0 [2.5.1]: https://github.com/mmacy/osrlib-python/compare/v2.5.0...v2.5.1 [2.5.0]: https://github.com/mmacy/osrlib-python/compare/v2.4.0...v2.5.0 [2.4.0]: https://github.com/mmacy/osrlib-python/compare/v2.3.0...v2.4.0 diff --git a/docs/guides/authoring-custom-content.md b/docs/guides/authoring-custom-content.md index b179db4..330abf2 100644 --- a/docs/guides/authoring-custom-content.md +++ b/docs/guides/authoring-custom-content.md @@ -256,7 +256,7 @@ miri = create_character( assert miri.spell_book == ("frost_dart",) ``` -Once the session starts, [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells], [`LearnSpell`][osrlib.crawl.commands.LearnSpell], [`CastSpell`][osrlib.crawl.commands.CastSpell], and battle `cast` declarations resolve bundled spells alongside built-in spells. [`MemberView`][osrlib.crawl.views.MemberView] lists `spell_book` and `memorized_spells` by spell ID (such as `"frost_dart"`), and [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names] contains the name of each one, read from `session.effective_spells`, so show those names rather than looking the ids up in `load_spells()`, which lacks the spells the adventure bundles: +Once the session starts, [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells], [`LearnSpell`][osrlib.crawl.commands.LearnSpell], [`CastSpell`][osrlib.crawl.commands.CastSpell], and battle `cast` declarations resolve bundled spells alongside built-in spells. [`MemberView`][osrlib.crawl.views.MemberView] lists `spell_book`, `preparable_spells`, `learnable_spells`, and `memorized_spells` by spell ID (such as `"frost_dart"`). A bundled spell is in [`preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells] for a divine caster whose class casts from its list and who has a slot at its level, and in [`learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] for an arcane caster whose class casts from its list and whose book has room at its level, so a player can find it before any member has it. [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names] contains the name of each listed spell and [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels] its level, both read from `session.effective_spells`, so show those names rather than looking the ids up in `load_spells()`, which lacks the spells the adventure bundles: ```{.python .no-run} bran = Character( @@ -895,7 +895,7 @@ assert COFFER.referee_notes not in view.model_dump_json() - **Read-only built-in loaders**: `load_classes`, `load_spells`, `load_monsters`, and `load_equipment` return cached, immutable SRD catalogs and provide no global registration or mutation API. Pass extended catalogs explicitly to kernel functions or bundle custom spells, monsters, and items on `Adventure`. - **Generated scrolls and NPC casters**: Randomly rolled treasure scrolls and NPC party spell lists draw exclusively from the built-in `load_spells()` catalog, never from `Adventure.spells`. -- **Cross-adventure spell books**: If a character enters a session with a spell ID from another adventure that is absent from `session.effective_spells`, the session rejects [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells] (`magic.memorize.unknown_spell`), [`CastSpell`][osrlib.crawl.commands.CastSpell] (`magic.cast.unknown_spell`), and battle `cast` declarations for that spell. While any unknown spell remains in the character's `spell_book`, the session also rejects [`LearnSpell`][osrlib.crawl.commands.LearnSpell] (`magic.book.unknown_spell`) because remaining spell-book capacity depends on every known spell's level. Energy drain cannot determine the level of an unknown memorized spell, so it leaves that entry untouched in `memorized_spells`. +- **Cross-adventure spell books**: If a character enters a session with a spell ID from another adventure that is absent from `session.effective_spells`, the session rejects [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells] (`magic.memorize.unknown_spell`), [`CastSpell`][osrlib.crawl.commands.CastSpell] (`magic.cast.unknown_spell`), and battle `cast` declarations for that spell. While any unknown spell remains in the character's `spell_book`, the session also rejects [`LearnSpell`][osrlib.crawl.commands.LearnSpell] (`magic.book.unknown_spell`) because remaining spell-book capacity depends on every known spell's level. Energy drain cannot determine the level of an unknown memorized spell, so it leaves that entry untouched in `memorized_spells`. In the player view, the character's [`learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] is empty while the book contains the unknown spell, and [`preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells] leaves the unknown id out. See [the class id index][classes-index] and [the spell id index][spells-index] for built-in IDs, and [the API reference](../reference/api/index.md) for full model definitions. diff --git a/docs/guides/views-and-visibility.md b/docs/guides/views-and-visibility.md index 01f90cf..ae85afb 100644 --- a/docs/guides/views-and-visibility.md +++ b/docs/guides/views-and-visibility.md @@ -30,9 +30,11 @@ assert "current_hp" not in player_group.model_dump() `PlayerView` includes the adventure and town names and descriptions, available town services and temple healing prices, the party's position and facing, the elapsed clock, fatigue and deprivation status, and the current `SessionMode`. -Each party member appears in `PlayerView.party` as a [`MemberView`][osrlib.crawl.views.MemberView] containing every stat needed to render a B/X character sheet: ID, name, race, class id and class name (`class_name`, which is right for a custom class too), level, title, alignment, XP and next-level XP threshold, current and maximum hit points, conditions, ability scores and modifiers, THAC0 and attack bonus, descending and ascending AC, saving throws, movement rate, languages, inventory, spell book, memorized spells, and thief skill chances. +Each party member appears in `PlayerView.party` as a [`MemberView`][osrlib.crawl.views.MemberView] containing every stat needed to render a B/X character sheet: ID, name, race, class id and class name (`class_name`, which is right for a custom class too), level, title, alignment, XP and next-level XP threshold, current and maximum hit points, conditions, ability scores and modifiers, THAC0 and attack bonus, descending and ascending AC, saving throws, movement rate, languages, inventory, spell book, spell slots at each spell level (`spell_slots`), the spells the member may prepare (`preparable_spells`) and learn (`learnable_spells`), memorized spells, and thief skill chances. -A member's spell book and memorized spells name each spell by id, and so does the `kind` of a spell's effect in `PlayerView.effects`. Show the names in [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names], keyed by those ids, and the names of reversed forms, like *darkness* for *light*, in [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names]. The view reads both from the session's catalog, so a spell the adventure bundles has its name there too. Neither includes a spell that is absent from the rest of the view, like one on a scroll. +[`MemberView.preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells] lists the spells the member may select in a [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells], and [`MemberView.learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] lists the spells the member may write into their spell book with [`LearnSpell`][osrlib.crawl.commands.LearnSpell]. Build your prepare and learn dialogs from them. Both are in the order of the session's catalog, and the session checks each command with the same rules that build the lists. A spell is in `preparable_spells` exactly when the spell and the member pass every check that `PrepareSpells` makes of one copy in its normal form, and the selection as a whole still has to fit the member's slots. An arcane caster may also select the reversed form of a listed spell that has an entry in `PlayerView.reversed_spell_names`. A spell is in `learnable_spells` exactly when the spell and the member pass every check that `LearnSpell` makes. A divine caster may prepare every spell on their class's list at the spell levels where they have a slot, including the spells the adventure bundles for that list. An arcane caster may prepare the spells in their book at those levels, and may learn the spells on their list that aren't in the book, at the spell levels where the book has room. Neither list depends on the moment, so each is the same before the party has slept, during an encounter or a battle, and while the member can't act, although the session refuses the commands then. To fill a prepare dialog, group `preparable_spells` by spell level, and at each level offer no more copies than [`MemberView.spell_slots`][osrlib.crawl.views.MemberView.spell_slots] gives there. + +A spell id appears in five places in the view: in a member's `spell_book`, `preparable_spells`, `learnable_spells`, and `memorized_spells`, and as the `kind` of a spell's effect in `PlayerView.effects`. Show the names in [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names], keyed by those ids, and the names of reversed forms, like *darkness* for *light*, in [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names]. Group spells by the level in [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels]. The view reads all three from the session's catalog, so a spell the adventure bundles has its name and level there too. They name only the spells whose ids the view shows. A spell the adventure bundles for a list that the party's classes don't cast from stays hidden. So does a spell at a spell level where the members can neither prepare nor learn it. A spell on a scroll is named only when the view shows its id in one of the five places: in a member's book, either list, or memorized copies, or as the kind of an effect on a member. Items work the same way. An inventory identifies a mundane stack by its template's catalog id, like `"holy_water"`, and a magic item or a gem or piece of jewellery by its instance id, like `"magic-item-0003"`, and the item events use the same ids. Show the names in [`PlayerView.item_names`][osrlib.crawl.views.PlayerView.item_names], a noun phrase for one with no article, like `"vial of holy water"`, and in [`PlayerView.item_names_plural`][osrlib.crawl.views.PlayerView.item_names_plural] for a count, so you can word "The party finds 2 vials of holy water". Both have a key for each item id that the inventories and the known piles show, and only for those ids. A mundane stack, carried or in a pile, is named as the session's catalog names it, so an item the adventure bundles has its name there too. The session gives the template each carried stack embeds the catalog's display names when it starts, when a save loads, and when [`AddMember`][osrlib.crawl.commands.AddMember] adds a member, so a stack from a 2.7.0 save, whose template has no display names, shows the catalog's names in `inventory` too, and the next save writes them. A carried stack whose id the catalog lacks, such as an item another adventure bundled, keeps the names its template has. A valuable is named by its kind, `"gem"` or `"piece of jewellery"`, whereas the inventory's `valuables` contain the piece's name and value. A potion drunk before the party knew what it was is identified and used up in one command, so no view contains its name, and the [`ItemIdentifiedEvent`][osrlib.crawl.events.ItemIdentifiedEvent] contains its names instead. diff --git a/src/osrlib/core/spells.py b/src/osrlib/core/spells.py index 4362411..a8b2e17 100644 --- a/src/osrlib/core/spells.py +++ b/src/osrlib/core/spells.py @@ -1395,30 +1395,14 @@ def memorize_spells( except ValueError: rejections.append(Rejection(code="magic.memorize.unknown_spell", params={"spell": selection.spell_id})) continue - if template.spell_list != profile.spell_list: - rejections.append( - Rejection( - code="magic.memorize.wrong_list", - params={"spell": selection.spell_id, "list": template.spell_list}, - ) - ) + rejection = _selection_rejection(caster, profile, template, selection) + if rejection is not None: + rejections.append(rejection) continue - if profile.kind == "divine" and selection.reversed: - rejections.append( - Rejection(code="magic.memorize.divine_reverses_at_cast", params={"spell": selection.spell_id}) - ) - continue - if profile.kind == "arcane": - if selection.spell_id not in getattr(caster, "spell_book", ()): - rejections.append(Rejection(code="magic.memorize.not_in_book", params={"spell": selection.spell_id})) - continue - if selection.reversed and template.reversed_form is None: - rejections.append(Rejection(code="magic.memorize.not_reversible", params={"spell": selection.spell_id})) - continue counts[template.level] = counts.get(template.level, 0) + 1 slots = definition.row(caster.level).spell_slots for spell_level, count in sorted(counts.items()): - allowed = slots[spell_level - 1] if spell_level <= len(slots) else 0 + allowed = _slot_count(slots, spell_level) if count > allowed: rejections.append( Rejection( @@ -1436,6 +1420,57 @@ def memorize_spells( return MemorizationResult(events=(event,)) +def _slot_count(slots: Sequence[int], spell_level: int) -> int: + """Return a progression row's slot count at a spell level, which is 0 past the end of the row.""" + return slots[spell_level - 1] if spell_level <= len(slots) else 0 + + +def _selection_rejection( + caster: Caster, profile: CasterProfile, template: SpellTemplate, selection: MemorizedSpell +) -> Rejection | None: + """Return why `memorize_spells` refuses one copy for its spell and its form, or None when it doesn't. + + These are the checks of a single copy against the caster, once the spell is known to be in the catalog. The + slot counts are checked over the whole selection, with `_slot_count`. + """ + if template.spell_list != profile.spell_list: + return Rejection( + code="magic.memorize.wrong_list", params={"spell": selection.spell_id, "list": template.spell_list} + ) + if profile.kind == "divine" and selection.reversed: + return Rejection(code="magic.memorize.divine_reverses_at_cast", params={"spell": selection.spell_id}) + if profile.kind == "arcane": + if selection.spell_id not in getattr(caster, "spell_book", ()): + return Rejection(code="magic.memorize.not_in_book", params={"spell": selection.spell_id}) + if selection.reversed and template.reversed_form is None: + return Rejection(code="magic.memorize.not_reversible", params={"spell": selection.spell_id}) + return None + + +def _preparable_spell_ids(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> tuple[str, ...]: + """Return the ids of the spells `memorize_spells` accepts one normal-form copy of, in the catalog's order. + + A spell is here exactly when that one-copy selection gets none of the rejections that belong to the spell and + the caster: `not_a_caster`, `unknown_spell`, `wrong_list`, `not_in_book`, and `slots_exceeded`. Every spell in + the catalog is known, and one copy exceeds the slots at its level only when there are none. + """ + profile = caster_profile(definition) + if profile is None: + return () + slots = definition.row(caster.level).spell_slots + book = set(getattr(caster, "spell_book", ())) if profile.kind == "arcane" else None + return tuple( + template.id + for template in catalog.spells + # The first three tests skip only spells that the checks after them refuse, and they cost less than the + # MemorizedSpell and Rejection models those checks build. `_selection_rejection` decides every spell left. + if template.spell_list == profile.spell_list + and (book is None or template.id in book) + and _slot_count(slots, template.level) > 0 + and _selection_rejection(caster, profile, template, MemorizedSpell(spell_id=template.id)) is None + ) + + class SpellBookResult(_Model): """What came of a call to [`add_spell_to_book`][osrlib.core.spells.add_spell_to_book]. @@ -1615,35 +1650,82 @@ def add_spell_to_book( assert [rejection.code for rejection in refused.rejections] == ["magic.book.wrong_list"] ``` """ + rejection = _book_rejection(caster, definition, catalog, spell_id) + if rejection is not None: + return SpellBookResult(rejections=(rejection,)) + caster.spell_book = (*caster.spell_book, spell_id) + return SpellBookResult(events=(SpellBookUpdatedEvent(caster_id=_entity_id(caster), spell_id=spell_id),)) + + +def _book_rejection( + caster: Caster, definition: ClassDefinition, catalog: SpellCatalog, spell_id: str +) -> Rejection | None: + """Return why `add_spell_to_book` refuses a spell, or None when it accepts it. + + The checks run in a fixed order and stop at the first that fails. This function makes the checks of the class + and of the spell's id, and `_book_template_rejection` makes the rest. + """ profile = caster_profile(definition) if profile is None or profile.kind != "arcane": - return SpellBookResult(rejections=(Rejection(code="magic.book.not_arcane", params={"class": definition.id}),)) + return Rejection(code="magic.book.not_arcane", params={"class": definition.id}) try: template = catalog.get(spell_id) except ValueError: - return SpellBookResult(rejections=(Rejection(code="magic.book.unknown_spell", params={"spell": spell_id}),)) + return Rejection(code="magic.book.unknown_spell", params={"spell": spell_id}) + return _book_template_rejection(caster, definition, catalog, profile, template) + + +def _book_template_rejection( + caster: Caster, + definition: ClassDefinition, + catalog: SpellCatalog, + profile: CasterProfile, + template: SpellTemplate, + *, + open_slots: tuple[int, ...] | None = None, +) -> Rejection | None: + """Return why `add_spell_to_book` refuses a spell of the catalog for an arcane caster, or None when it accepts it. + + `profile` is the caster's arcane profile, and `template` is the spell from `catalog`. `open_slots` is the + caster's `open_book_capacity`, which a caller checking many spells against one book passes so that it's computed + once. Without it, the capacity is computed only for a spell that passes every earlier check. + """ if template.spell_list != profile.spell_list: - return SpellBookResult( - rejections=( - Rejection(code="magic.book.wrong_list", params={"spell": spell_id, "list": template.spell_list}), - ) + return Rejection(code="magic.book.wrong_list", params={"spell": template.id, "list": template.spell_list}) + if template.id in caster.spell_book: + return Rejection(code="magic.book.duplicate", params={"spell": template.id}) + if open_slots is None: + open_slots = open_book_capacity(caster, definition, catalog) + if _slot_count(open_slots, template.level) == 0: + capacity = _slot_count(definition.row(caster.level).spell_slots, template.level) + return Rejection( + code="magic.book.capacity_exceeded", + params={"spell": template.id, "spell_level": template.level, "capacity": capacity}, ) - if spell_id in caster.spell_book: - return SpellBookResult(rejections=(Rejection(code="magic.book.duplicate", params={"spell": spell_id}),)) + return None + + +def _learnable_spell_ids(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> tuple[str, ...]: + """Return the ids of the spells `add_spell_to_book` accepts, in the catalog's order. + + It's empty for a class with no spell book. Like `open_book_capacity`, it raises `ValueError` when the book has a + spell that isn't in `catalog`. + """ + profile = caster_profile(definition) + if profile is None or profile.kind != "arcane": + return () open_slots = open_book_capacity(caster, definition, catalog) - if template.level > len(open_slots) or open_slots[template.level - 1] == 0: - slots = definition.row(caster.level).spell_slots - capacity = slots[template.level - 1] if template.level <= len(slots) else 0 - return SpellBookResult( - rejections=( - Rejection( - code="magic.book.capacity_exceeded", - params={"spell": spell_id, "spell_level": template.level, "capacity": capacity}, - ), - ) - ) - caster.spell_book = (*caster.spell_book, spell_id) - return SpellBookResult(events=(SpellBookUpdatedEvent(caster_id=_entity_id(caster), spell_id=spell_id),)) + book = set(caster.spell_book) + return tuple( + template.id + for template in catalog.spells + # The first three tests skip only spells that `_book_template_rejection` refuses, without building the + # Rejection model. It decides every spell left. + if template.spell_list == profile.spell_list + and template.id not in book + and _slot_count(open_slots, template.level) > 0 + and _book_template_rejection(caster, definition, catalog, profile, template, open_slots=open_slots) is None + ) def forget_excess_memorized(caster: Caster, definition: ClassDefinition, catalog: SpellCatalog) -> list[Event]: diff --git a/src/osrlib/crawl/_spells.py b/src/osrlib/crawl/_spells.py index e74bf56..189ac2b 100644 --- a/src/osrlib/crawl/_spells.py +++ b/src/osrlib/crawl/_spells.py @@ -23,6 +23,8 @@ SpellCatalog, SpellEffect, SpellTemplate, + _learnable_spell_ids, + _preparable_spell_ids, add_spell_to_book, cast_spell, caster_profile, @@ -57,16 +59,46 @@ def _handle_learn_spell(session, command: LearnSpell) -> tuple[list[Rejection], if rejections: return rejections, [] catalog = session.effective_spells - known = {spell.id for spell in catalog.spells} - # The room left at a spell level depends on the level of each spell already in the book, so - # the session can't check a book with a spell its catalog doesn't have. - unknown = next((spell_id for spell_id in member.spell_book if spell_id not in known), None) + unknown = _unknown_book_spell(catalog, member) if unknown is not None: return [Rejection(code="magic.book.unknown_spell", params={"spell": unknown})], [] result = add_spell_to_book(member, member.definition, catalog, command.spell_id) return list(result.rejections), list(result.events) +def _unknown_book_spell(catalog: SpellCatalog, member: Character) -> str | None: + """Return the first id in the member's spell book that the catalog lacks, or None when it has them all. + + The room left at a spell level depends on the level of each spell already in the book, so the session can't + check a book with a spell its catalog doesn't have, and `LearnSpell` refuses every spell while the book has one. + """ + if not member.spell_book: + return None + known = {spell.id for spell in catalog.spells} + return next((spell_id for spell_id in member.spell_book if spell_id not in known), None) + + +def _preparable_spells(session, member: Character) -> tuple[str, ...]: + """Return the ids of the spells a `PrepareSpells` accepts one normal-form copy of, in the catalog's order. + + The checks that belong to the moment don't apply: whether the party has slept, the session's mode, and whether + the member can act. It's the member view's `preparable_spells`. + """ + return _preparable_spell_ids(member, member.definition, session.effective_spells) + + +def _learnable_spells(session, member: Character) -> tuple[str, ...]: + """Return the ids of the spells a `LearnSpell` accepts, in the catalog's order. + + It makes the same checks as `_handle_learn_spell` after `_member_able`, which checks the moment, so it's the + member view's `learnable_spells`. + """ + catalog = session.effective_spells + if _unknown_book_spell(catalog, member) is not None: + return () + return _learnable_spell_ids(member, member.definition, catalog) + + def _handle_cast_spell(session, command: CastSpell) -> tuple[list[Rejection], list[Event]]: member, rejections = _member_able(session, command.character_id) if rejections: diff --git a/src/osrlib/crawl/commands.py b/src/osrlib/crawl/commands.py index 8e7d59d..8730b82 100644 --- a/src/osrlib/crawl/commands.py +++ b/src/osrlib/crawl/commands.py @@ -1658,7 +1658,16 @@ class PrepareSpells(Command): to memorize more than one copy of it. The number at each spell level has to fit the caster's slots at that level, and an empty tuple clears the list. The caster's current list is in - [`MemberView.memorized_spells`][osrlib.crawl.views.MemberView.memorized_spells].""" + [`MemberView.memorized_spells`][osrlib.crawl.views.MemberView.memorized_spells]. + + Choose the spells from + [`MemberView.preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells], which lists + each spell that this caster may select in its normal form. An arcane caster may also select the + reversed form of a listed spell that has an entry in + [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names]. Group + the list by [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels], and at each + spell level select no more copies than the count there in + [`MemberView.spell_slots`][osrlib.crawl.views.MemberView.spell_slots].""" class LearnSpell(Command): @@ -1703,7 +1712,9 @@ class LearnSpell(Command): built-in spell (see the [spell id index](https://mmacy.github.io/osrlib-python/reference/content-ids/spells/)) or one the adventure bundles. It has to be on the spell list of the caster's class. At each spell - level, no more spells fit in the book than the caster has slots at that level.""" + level, no more spells fit in the book than the caster has slots at that level. + [`MemberView.learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] lists each + spell that this caster may learn, so build a learn dialog from it.""" class CastSpell(Command): diff --git a/src/osrlib/crawl/session.py b/src/osrlib/crawl/session.py index 0403ebd..7d5317a 100644 --- a/src/osrlib/crawl/session.py +++ b/src/osrlib/crawl/session.py @@ -1141,13 +1141,19 @@ def effective_spells(self) -> SpellCatalog: session that turns a spell id into a spell reads it: preparing, learning, and casting a spell, a `cast` declaration in a battle, reading a scroll, an NPC adventurer's casting, the temple, and a level drain, which forgets the memorized spells a lower level has no slot for. - Use it to list the spells a caster can choose with - [`SpellCatalog.by_list`][osrlib.core.spells.SpellCatalog.by_list], or to read more of a spell - than its name. [`load_spells`][osrlib.data.load_spells] doesn't have the spells the adventure - bundles. To show the name of a spell whose id is in a player view, read + Use it to read more of a spell than its name. [`load_spells`][osrlib.data.load_spells] doesn't + have the spells the adventure bundles. To list the spells a party member may prepare or learn, + read [`MemberView.preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells] and + [`MemberView.learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells] in a player + view. The session builds them with the checks that `PrepareSpells` and `LearnSpell` make. A + list from [`SpellCatalog.by_list`][osrlib.core.spells.SpellCatalog.by_list] also contains spells + that the session refuses, such as one at a spell level where the member has no slot. To show + the name of a spell whose id is in a player view, read [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names] and - [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names], which - contain the names from this catalog, so a remote client that has only the view can show them. + [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names], and + read its level in [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels]. + They contain the names and levels from this catalog, so a remote client that has only the view + can show them. A character can have a spell in their spell book or memorized that this catalog doesn't have, like a caster from a party made for another adventure. The session leaves the id on diff --git a/src/osrlib/crawl/views.py b/src/osrlib/crawl/views.py index b69d44a..4ccd1c8 100644 --- a/src/osrlib/crawl/views.py +++ b/src/osrlib/crawl/views.py @@ -401,9 +401,74 @@ class of its own. An unarmoured fighter with AC 9 reads 7 with an unidentified c [`Character.languages`][osrlib.core.character.Character.languages] lists them.""" spell_book: tuple[str, ...] = () """The ids of the spells in the member's spell book, as in - [`Character.spell_book`][osrlib.core.character.Character.spell_book]. They're the spells the member - can choose from in a [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells]. Empty for a class that - has no spell book. To show a spell's name, look its id up in + [`Character.spell_book`][osrlib.core.character.Character.spell_book], in the order they were + written in. Empty for a class that has no spell book. An arcane caster prepares only from the + book, and `preparable_spells` lists the spells in it that the member has a slot for. To show a + spell's name, look its id up in + [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names].""" + spell_slots: tuple[int, ...] = () + """How many spells the member can memorize at each spell level, lowest level first, as in the + [`spell_slots`][osrlib.core.classes.ProgressionRow.spell_slots] of the class's progression row + for the member's level. Entry `i` is the slot count at spell level `i + 1`. It comes from + [`Character.definition`][osrlib.core.character.Character.definition], so it's right for a custom + class too. + + A [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells] fits these counts: at each spell level, + select no more copies than the count there, and group `preparable_spells` by + [`PlayerView.spell_levels`][osrlib.crawl.views.PlayerView.spell_levels] to fill them. An arcane + caster's book has room at a spell level for this count less the spells the book already has + there. A 1st-level cleric has a count of 0 at every level, and a class that casts nothing has an + empty tuple.""" + preparable_spells: tuple[str, ...] = () + """The ids of the spells the member may select in a + [`PrepareSpells`][osrlib.crawl.commands.PrepareSpells], in the order of the session's catalog, + [`GameSession.effective_spells`][osrlib.crawl.session.GameSession.effective_spells]. Build a + prepare dialog from it. + + For an arcane caster, they're the spells in `spell_book` at the spell levels where the member has + a slot, so a spell that a lost level left in the book without a slot isn't here. For a divine + caster, they're the spells on the class's spell list at every spell level where the member has a + slot, and the spells the adventure bundles for that list are among them. A cleric has no slot + until 2nd level, so the tuple is empty for a 1st-level cleric. It's empty for a class that casts + nothing. + + A spell id is here exactly when a `PrepareSpells` that selects one copy of it in its normal form + is refused with none of these codes, which belong to the spell and the member: + `magic.memorize.not_a_caster`, `magic.memorize.unknown_spell`, `magic.memorize.wrong_list`, + `magic.memorize.not_in_book`, and `magic.memorize.slots_exceeded`. The tuple doesn't depend on + the moment, so it's the same before the party has slept (`magic.memorize.needs_sleep`), during an + encounter or a battle (`session.command.wrong_mode`), and while the member can't act + (`session.command.member_incapacitated`). The selections as a whole still have to fit + `spell_slots` at each spell level. + + The form of a copy is up to the caster's kind. An arcane caster may select the reversed form of a + spell that has an entry in + [`PlayerView.reversed_spell_names`][osrlib.crawl.views.PlayerView.reversed_spell_names], and the + session refuses the reversed form of any other spell with `magic.memorize.not_reversible`. A + divine caster selects the normal form and chooses the form when casting, and the session refuses a + reversed selection with `magic.memorize.divine_reverses_at_cast`. To show a spell's name, look its + id up in [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names].""" + learnable_spells: tuple[str, ...] = () + """The ids of the spells the member may write into their spell book with + [`LearnSpell`][osrlib.crawl.commands.LearnSpell], in the order of the session's catalog, + [`GameSession.effective_spells`][osrlib.crawl.session.GameSession.effective_spells]. Build a learn + dialog from it. + + They're the spells on the class's spell list that aren't in `spell_book`, at each spell level + where the book has room. The room at a spell level is the member's count there in `spell_slots`, + less the spells the book already has at that level. The spells the adventure bundles for that list + are among them. The tuple is empty for a divine caster and for a class that casts nothing, + because neither keeps a spell book. It's also empty while the book has a spell that the session's + catalog doesn't have, because the session can't tell that spell's level, and so can't tell how + much room the book has left. + + A spell id is here exactly when a `LearnSpell` for it is refused with none of these codes, which + belong to the spell and the member: `magic.book.not_arcane`, `magic.book.unknown_spell`, + `magic.book.wrong_list`, `magic.book.duplicate`, and `magic.book.capacity_exceeded`. The tuple + doesn't depend on the moment, so it's the same during an encounter or a battle + (`session.command.wrong_mode`) and while the member can't act + (`session.command.member_incapacitated`). Learning one spell can fill the book at that spell's + level, so read the view again after each `LearnSpell`. To show a spell's name, look its id up in [`PlayerView.spell_names`][osrlib.crawl.views.PlayerView.spell_names].""" thief_skills: dict[str, int] = {} """The member's chance at each thief skill at their level, keyed by the skill field names of @@ -1118,9 +1183,11 @@ class PlayerView(_Model): """The name of each spell whose id the view shows, keyed by spell id, like `{"magic_missile": "Magic Missile"}`. Show these names, not the ids. - A spell id appears in three places in the view: in a member's - [`spell_book`][osrlib.crawl.views.MemberView.spell_book], as the `spell_id` of a copy in a member's - [`memorized_spells`][osrlib.crawl.views.MemberView.memorized_spells], and as the + A spell id appears in five places in the view: in a member's + [`spell_book`][osrlib.crawl.views.MemberView.spell_book], + [`preparable_spells`][osrlib.crawl.views.MemberView.preparable_spells], and + [`learnable_spells`][osrlib.crawl.views.MemberView.learnable_spells], as the `spell_id` of a copy in + a member's [`memorized_spells`][osrlib.crawl.views.MemberView.memorized_spells], and as the [`kind`][osrlib.crawl.views.MemberEffectView.kind] of an effect in `effects`, because a spell's effect has the spell's id as its kind unless the spell's data gives it a kind of its own. Every one of those ids that the session's catalog, @@ -1129,8 +1196,10 @@ class PlayerView(_Model): bundles has its name here too, which [`load_spells`][osrlib.data.load_spells] doesn't have. An effect kind that isn't a spell id, like a torch's `"light"`, has no entry. - It names no spell whose id the view doesn't show, so the spells on a scroll stay hidden. A spell id - on a member that the session's catalog doesn't have, like one from a party made for another + It names no spell whose id the view doesn't show. So a spell the adventure bundles for a list that + no member casts from stays hidden, and so does a spell at a level where no member could prepare or + learn it. A spell on a scroll is named only when a member could prepare or learn it anyway. A spell + id on a member that the session's catalog doesn't have, like one from a party made for another adventure, has no entry either, and the session refuses to prepare or cast that spell. The name here is always the spell's normal form. For a copy prepared reversed, show its name from `reversed_spell_names`.""" @@ -1147,6 +1216,17 @@ class PlayerView(_Model): [`memorized_spells`][osrlib.crawl.views.MemberView.memorized_spells]. A divine caster prepares the normal form and chooses the form when casting, so every memorized copy of a reversible spell can be cast either way. To offer that choice, show both names.""" + spell_levels: dict[str, int] = {} + """The level of each spell in `spell_names`, keyed by spell id, like + `{"magic_missile": 1, "web": 2}`. Group a prepare or learn dialog by it, because a member's slots + are counted per spell level, in + [`MemberView.spell_slots`][osrlib.crawl.views.MemberView.spell_slots]. + + Each value is the spell's [`level`][osrlib.core.spells.SpellTemplate.level], read from the same + catalog as `spell_names`, so a spell the adventure bundles has the level its author gave it. A + spell id belongs to exactly one spell list, like `light_mu` to the magic-user's and `light_c` to + the cleric's, so each id has one level for every class that casts from its list, like the elf, + who casts from the magic-user's list.""" item_names: dict[str, str] = {} """What to call one of each item whose id the view shows, keyed by that id, like `{"torch": "torch", "holy_water": "vial of holy water", "magic-item-0003": "potion"}`. Show these @@ -1583,7 +1663,7 @@ def build_player_view(session) -> PlayerView: for member_id, state in session.deprivation.items() if state.worst > 0 } - spell_names, reversed_spell_names = _spell_names(session, members, effects) + spell_names, reversed_spell_names, spell_levels = _spell_names(session, members, effects) item_names, item_names_plural = _item_names(session, known_piles.values()) return PlayerView( adventure_name=session.adventure.name, @@ -1608,6 +1688,7 @@ def build_player_view(session) -> PlayerView: effects=effects, spell_names=spell_names, reversed_spell_names=reversed_spell_names, + spell_levels=spell_levels, item_names=item_names, item_names_plural=item_names_plural, fatigued=fatigued, @@ -1619,25 +1700,34 @@ def build_player_view(session) -> PlayerView: ) -def _spell_names(session, members, effects) -> tuple[dict[str, str], dict[str, str]]: - # Only the ids the view already shows are named, so a scroll's spells stay hidden. An id the - # session's catalog lacks, and an effect kind that is no spell's id, get no entry. +def _spell_names(session, members, effects) -> tuple[dict[str, str], dict[str, str], dict[str, int]]: + """The view's `spell_names`, `reversed_spell_names`, and `spell_levels`, for the spell ids the view shows. + + Only the ids the view already shows are named: those in the members' books, memorized copies, and the two lists + of what each member may prepare or learn, and the effect kinds. So a spell that the members can't choose stays + hidden, such as one on a scroll or one on a list that the party's classes don't cast from. An id the session's + catalog lacks, and an effect kind that is no spell's id, get no entry. + """ catalog = {spell.id: spell for spell in session.effective_spells.spells} shown = [ *(spell_id for member in members for spell_id in member.spell_book), *(copy["spell_id"] for member in members for copy in member.memorized_spells), *(effect.kind for effect in effects), + *(spell_id for member in members for spell_id in member.preparable_spells), + *(spell_id for member in members for spell_id in member.learnable_spells), ] names: dict[str, str] = {} reversed_names: dict[str, str] = {} + levels: dict[str, int] = {} for spell_id in shown: spell = catalog.get(spell_id) if spell is None or spell_id in names: continue names[spell_id] = spell.name + levels[spell_id] = spell.level if spell.reversed_form is not None: reversed_names[spell_id] = spell.reversed_form.name - return names, reversed_names + return names, reversed_names, levels def _pile_view(pile: DropPile) -> PileView: @@ -1953,6 +2043,8 @@ def _canonical_edge(cell: Position, direction: Direction) -> str: def _member_view(session, member) -> MemberView: """One member's sheet, read from the live character.""" + from osrlib.crawl._spells import _learnable_spells, _preparable_spells + definition = member.definition thief_skills = {} if definition.thief_skills: @@ -1992,6 +2084,9 @@ def _member_view(session, member) -> MemberView: movement_rate_feet=member.movement_rate(session.ruleset), languages=member.languages, spell_book=member.spell_book, + spell_slots=definition.row(member.level).spell_slots, + preparable_spells=_preparable_spells(session, member), + learnable_spells=_learnable_spells(session, member), thief_skills=thief_skills, ) diff --git a/tests/saves/view_spell_lists_2.7.0.json b/tests/saves/view_spell_lists_2.7.0.json new file mode 100644 index 0000000..6685913 --- /dev/null +++ b/tests/saves/view_spell_lists_2.7.0.json @@ -0,0 +1,1724 @@ +{ + "engine_version": "2.7.0", + "kind": "save", + "payload": { + "adventure": { + "description": "", + "dungeons": [ + { + "id": "crypt", + "levels": [ + { + "areas": [], + "edges": { + "1,0:west": { + "door": null, + "kind": "open" + } + }, + "entrance": [ + 0, + 0 + ], + "features": [], + "guidance": "", + "height": 1, + "number": 1, + "transitions": [], + "wandering": { + "chance_in_six": 1, + "interval_turns": 2, + "table": null + }, + "width": 2 + } + ], + "name": "Crypt" + } + ], + "hooks": [], + "items": [], + "monsters": [], + "name": "A", + "party": null, + "quests": [], + "spells": [ + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "Instant", + "duration_spec": { + "amount": null, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "instant", + "per_level": 0, + "unit": null + }, + "id": "balm", + "intro": "This spell has two usages:", + "level": 1, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "heal", + "modifiers": [], + "params": { + "dice": "1d6+1" + } + }, + "key": "heal", + "manual": false, + "prose": "Healing a living subject: Restores 1d6+1 hit points of damage. This cannot raise the subject\u2019s hit points above their normal maximum.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + }, + { + "effect": { + "condition": null, + "cures_conditions": [ + "paralysed" + ], + "cures_effect_kinds": [], + "kind": "cure", + "modifiers": [], + "params": {} + }, + "key": "cure_paralysis", + "manual": false, + "prose": "Curing paralysis: Paralysing effects are negated.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + } + ], + "name": "Balm", + "overrides_applied": [], + "range": "The caster or a creature touched", + "range_spec": { + "feet": null, + "kind": "touch", + "per_level_feet": null + }, + "reversed_form": { + "duration": null, + "duration_spec": null, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "damage", + "modifiers": [], + "params": { + "dice": "1d6+1", + "touch_attack": true + } + }, + "key": "harm", + "manual": false, + "prose": "Inflicts 1d6+1 hit points of damage to a touched creature. In combat, a melee attack roll is required.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + } + ], + "name": "Bane", + "prose": "Inflicts 1d6+1 hit points of damage to a touched creature. In combat, a melee attack roll is required." + }, + "spell_list": "cleric" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "Instant / Permanent (curse)", + "duration_spec": { + "amount": null, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "instant", + "per_level": 0, + "unit": null + }, + "id": "sanctum", + "intro": "This spell removes a single curse from the subject. It may allow a character to discard a cursed magic item.", + "level": 3, + "modes": [ + { + "effect": null, + "key": "cast", + "manual": true, + "prose": "This spell removes a single curse from the subject. It may allow a character to discard a cursed magic item.", + "save": null, + "targeting": null + } + ], + "name": "Sanctum", + "overrides_applied": [], + "range": "The caster or a creature touched", + "range_spec": { + "feet": null, + "kind": "touch", + "per_level_feet": null + }, + "reversed_form": { + "duration": "Permanent (curse)", + "duration_spec": { + "amount": null, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "permanent", + "per_level": 0, + "unit": null + }, + "modes": [ + { + "effect": null, + "key": "cast", + "manual": true, + "prose": "Places a deleterious effect upon a creature, if it fails a save versus spells.\nEffects: The exact form and effects of the curse are determined by the caster.\nMaximum possible effects include: A \u20132 penalty to saving throws, a \u20134 penalty to attack rolls, reducing an ability score by 50%.\nMultiple curses: May afflict a creature, as long as each has a different effect.\nReferee judgement: The referee should judge the effects of this spell and may turn overly powerful curses back onto the caster!", + "save": null, + "targeting": null + } + ], + "name": "Curse", + "prose": "Places a deleterious effect upon a creature, if it fails a save versus spells.\nEffects: The exact form and effects of the curse are determined by the caster.\nMaximum possible effects include: A \u20132 penalty to saving throws, a \u20134 penalty to attack rolls, reducing an ability score by 50%.\nMultiple curses: May afflict a creature, as long as each has a different effect.\nReferee judgement: The referee should judge the effects of this spell and may turn overly powerful curses back onto the caster!" + }, + "spell_list": "cleric" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "2 turns", + "duration_spec": { + "amount": 2, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "fixed", + "per_level": 0, + "unit": "turn" + }, + "id": "glimmer", + "intro": "Conjures a barrier of magic that gives the caster an improved AC:", + "level": 1, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "modifiers", + "modifiers": [ + { + "dice": null, + "element": null, + "from_item": false, + "kind": "ac_set_vs_missile", + "melee_only": false, + "save_categories": [], + "value": 2, + "versus_other_alignment": false + }, + { + "dice": null, + "element": null, + "from_item": false, + "kind": "ac_set", + "melee_only": false, + "save_categories": [], + "value": 4, + "versus_other_alignment": false + } + ], + "params": {} + }, + "key": "shield", + "manual": false, + "prose": "Conjures a barrier of magic that gives the caster an improved AC:\nAgainst missile attacks: AC 2 [17].\nAgainst other attacks: AC 4 [15].", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "self", + "shape": null + } + } + ], + "name": "Glimmer", + "overrides_applied": [], + "range": "The caster", + "range_spec": { + "feet": null, + "kind": "caster", + "per_level_feet": null + }, + "reversed_form": null, + "spell_list": "magic_user" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "48 turns", + "duration_spec": { + "amount": 48, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "fixed", + "per_level": 0, + "unit": "turn" + }, + "id": "mire", + "intro": "Conjures a volume of sticky webbing, blocking a 10\u2019 cube area.", + "level": 2, + "modes": [ + { + "effect": { + "condition": "entangled", + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "condition", + "modifiers": [], + "params": { + "augmented_strength_rounds": 4, + "effect_kind": "web", + "escape_dice": "2d4", + "escape_unit": "turn", + "giant_strength_rounds": 2 + } + }, + "key": "entangle", + "manual": false, + "prose": "Conjures a volume of sticky webbing, blocking a 10\u2019 cube area.\nEntanglement: Creatures caught within a web become entangled among the gluey fibres. Entangled creatures can\u2019t move, but can break free depending on their strength (see below).\nFlammable: The web can be destroyed by fire in two rounds. All creatures caught within flaming webs suffer 1d6 damage from the flames.\nBreaking free: Depends on STR:\nNormal human range: The creature can break free in 2d4 turns.\nMagically augmented STR above 18: The creature can break free in 4 rounds.\nGiant strength: The creature can break free in 2 rounds.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": { + "side_feet": 10 + }, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "area", + "shape": "cube" + } + } + ], + "name": "Mire", + "overrides_applied": [], + "range": "10\u2019", + "range_spec": { + "feet": 10, + "kind": "feet", + "per_level_feet": null + }, + "reversed_form": null, + "spell_list": "magic_user" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "Instant", + "duration_spec": { + "amount": null, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "instant", + "per_level": 0, + "unit": null + }, + "id": "mend_wounds", + "intro": "This spell has two usages:", + "level": 1, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "heal", + "modifiers": [], + "params": { + "dice": "1d6+1" + } + }, + "key": "heal", + "manual": false, + "prose": "Healing a living subject: Restores 1d6+1 hit points of damage. This cannot raise the subject\u2019s hit points above their normal maximum.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + }, + { + "effect": { + "condition": null, + "cures_conditions": [ + "paralysed" + ], + "cures_effect_kinds": [], + "kind": "cure", + "modifiers": [], + "params": {} + }, + "key": "cure_paralysis", + "manual": false, + "prose": "Curing paralysis: Paralysing effects are negated.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + } + ], + "name": "Mend Wounds", + "overrides_applied": [], + "range": "The caster or a creature touched", + "range_spec": { + "feet": null, + "kind": "touch", + "per_level_feet": null + }, + "reversed_form": { + "duration": null, + "duration_spec": null, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "damage", + "modifiers": [], + "params": { + "dice": "1d6+1", + "touch_attack": true + } + }, + "key": "harm", + "manual": false, + "prose": "Inflicts 1d6+1 hit points of damage to a touched creature. In combat, a melee attack roll is required.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + } + ], + "name": "Cause Light Wounds", + "prose": "Inflicts 1d6+1 hit points of damage to a touched creature. In combat, a melee attack roll is required." + }, + "spell_list": "warden" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "6 turns", + "duration_spec": { + "amount": 6, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": null, + "kind": "fixed", + "per_level": 0, + "unit": "turn" + }, + "id": "ward_of_ages", + "intro": "May be used in one of two situations:", + "level": 2, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "modifiers", + "modifiers": [ + { + "dice": null, + "element": null, + "from_item": false, + "kind": "attack_bonus", + "melee_only": false, + "save_categories": [], + "value": 1, + "versus_other_alignment": false + }, + { + "dice": null, + "element": null, + "from_item": false, + "kind": "damage_bonus", + "melee_only": false, + "save_categories": [], + "value": 1, + "versus_other_alignment": false + }, + { + "dice": null, + "element": null, + "from_item": false, + "kind": "morale_bonus", + "melee_only": false, + "save_categories": [], + "value": 1, + "versus_other_alignment": false + } + ], + "params": {} + }, + "key": "battle", + "manual": false, + "prose": "Battle: Allies within a 20\u2019 square area who are not yet in melee gain a +1 bonus to attack and damage rolls and a +1 bonus to morale.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": { + "side_feet": 20 + }, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "area", + "shape": "square" + } + }, + { + "effect": null, + "key": "ritual", + "manual": true, + "prose": "Ritual: Casting bless may also form part of rituals of purification or consecration, at the referee\u2019s discretion.", + "save": null, + "targeting": null + } + ], + "name": "Ward Of Ages", + "overrides_applied": [], + "range": "60\u2019", + "range_spec": { + "feet": 60, + "kind": "feet", + "per_level_feet": null + }, + "reversed_form": { + "duration": null, + "duration_spec": null, + "modes": [ + { + "effect": { + "condition": null, + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "modifiers", + "modifiers": [ + { + "dice": null, + "element": null, + "from_item": false, + "kind": "attack_bonus", + "melee_only": false, + "save_categories": [], + "value": -1, + "versus_other_alignment": false + }, + { + "dice": null, + "element": null, + "from_item": false, + "kind": "damage_bonus", + "melee_only": false, + "save_categories": [], + "value": -1, + "versus_other_alignment": false + }, + { + "dice": null, + "element": null, + "from_item": false, + "kind": "morale_bonus", + "melee_only": false, + "save_categories": [], + "value": -1, + "versus_other_alignment": false + } + ], + "params": {} + }, + "key": "battle", + "manual": false, + "prose": "Incurs a -1 penalty to morale checks, attack rolls, and damage rolls of enemies within a 20\u2019 square area. A save versus spells is allowed to resist the blight.", + "save": { + "category": "spells", + "modifier": 0, + "on_save": "negates" + }, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": { + "side_feet": 20 + }, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "area", + "shape": "square" + } + } + ], + "name": "Blight", + "prose": "Incurs a -1 penalty to morale checks, attack rolls, and damage rolls of enemies within a 20\u2019 square area. A save versus spells is allowed to resist the blight." + }, + "spell_list": "warden" + }, + { + "conjured_monster_ids": [], + "conjured_monsters": [], + "duration": "4d4 turns", + "duration_spec": { + "amount": null, + "concentration_cap_amount": null, + "concentration_cap_unit": null, + "dice": "4d4", + "kind": "fixed", + "per_level": 0, + "unit": "turn" + }, + "id": "hex", + "intro": "Causes creatures (except undead) to fall into a magical slumber. The spell may target either:", + "level": 1, + "modes": [ + { + "effect": { + "condition": "asleep", + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "condition", + "modifiers": [], + "params": { + "excludes_undead": true, + "hd_bonus_required": true, + "hd_count": 4 + } + }, + "key": "single_4_plus", + "manual": false, + "prose": "A single creature with 4+1 Hit Dice (see Hit point modifiers).", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": null, + "hd_cap": null, + "hd_min": null, + "mode": "single", + "shape": null + } + }, + { + "effect": { + "condition": "asleep", + "cures_conditions": [], + "cures_effect_kinds": [], + "kind": "condition", + "modifiers": [], + "params": { + "excludes_hd_4_plus": true, + "excludes_undead": true + } + }, + "key": "hd_budget", + "manual": false, + "prose": "A total of 2d8 Hit Dice of creatures of 4 HD or lower each.", + "save": null, + "targeting": { + "count": null, + "count_dice": null, + "dimensions": {}, + "hd_budget_dice": "2d8", + "hd_cap": 4, + "hd_min": null, + "mode": "hd_budget", + "shape": null + } + } + ], + "name": "Hex", + "overrides_applied": [], + "range": "240\u2019", + "range_spec": { + "feet": 240, + "kind": "feet", + "per_level_feet": null + }, + "reversed_form": null, + "spell_list": "witch" + } + ], + "town": { + "description": "", + "healing_prices": {}, + "name": "Threshold", + "services": [], + "travel_turns": { + "crypt": 1 + } + }, + "triggers": [] + }, + "allocator": { + "counters": { + "character": 10 + } + }, + "battle": null, + "clock_rounds": 2880, + "command_log": [ + { + "command_type": "rest", + "hidden": false, + "kind": "night", + "source": null + } + ], + "death_records": {}, + "defeated_monsters": [], + "deprivation": {}, + "dungeon_state": { + "doors": {}, + "emptied_caches": [], + "explored": {}, + "found_traps": [], + "found_tricks": [], + "generated_caches": {}, + "generated_lair_hoards": [], + "generated_treasure_areas": [], + "inspect_attempts": {}, + "listen_attempts": {}, + "location": { + "dungeon_id": null, + "facing": null, + "kind": "town", + "level_number": null, + "position": null + }, + "lock_failures": {}, + "piles": {}, + "removal_attempts": {}, + "removed_traps": [], + "resolved_encounters": [], + "search_attempts": {}, + "seen": {}, + "sprung_traps": [] + }, + "encounter": null, + "event_log": [ + { + "code": "exploration.rest.rested", + "event_type": "rested", + "kind": "night", + "visibility": "player" + } + ], + "exploration": { + "alerted_areas": [], + "heard_areas": [], + "last_prepared_sleep": {}, + "noise_since_check": false, + "odometer_thirds": 0, + "provisions_day": 0, + "sleep_count": 1, + "turns_since_rest": 0, + "wandering_counter": 0 + }, + "fired_triggers": [], + "flags": {}, + "journal": [], + "ledger": { + "effects": [] + }, + "listener_state": {}, + "master_seed": 7, + "mode": "town", + "monsters": [], + "npcs": [], + "party": { + "members": [ + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "fighter", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0001", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 3, + "max_hp": 400, + "memorized_spells": [], + "name": "Hild", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 4000 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "thief", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0002", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 3, + "max_hp": 400, + "memorized_spells": [], + "name": "Nim", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 2400 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "elf", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0003", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 1, + "max_hp": 400, + "memorized_spells": [], + "name": "Aelin", + "nonregen_damage": 0, + "race": "elf", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [ + "sleep" + ], + "stat_modifiers": [], + "xp": 0 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "magic_user", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0004", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 3, + "max_hp": 400, + "memorized_spells": [], + "name": "Wren", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [ + "magic_missile", + "light_mu" + ], + "stat_modifiers": [], + "xp": 5000 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "magic_user", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0005", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 1, + "max_hp": 400, + "memorized_spells": [], + "name": "Sefa", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [ + "sleep", + "web" + ], + "stat_modifiers": [], + "xp": 0 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "magic_user", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0006", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 3, + "max_hp": 400, + "memorized_spells": [], + "name": "Ivo", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [ + "frost_dart", + "sleep" + ], + "stat_modifiers": [], + "xp": 5000 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "cleric", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0007", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 1, + "max_hp": 400, + "memorized_spells": [], + "name": "Tam", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 0 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "cleric", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0008", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 2, + "max_hp": 400, + "memorized_spells": [], + "name": "Oswin", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 1500 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "cleric", + "conditions": [], + "current_hp": 400, + "custom_class": null, + "extra_languages": [], + "id": "character-0009", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 4, + "max_hp": 400, + "memorized_spells": [], + "name": "Mara", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 6000 + }, + { + "alignment": "lawful", + "carrying_treasure": false, + "class_id": "warden", + "conditions": [], + "current_hp": 400, + "custom_class": { + "abilities": [ + { + "manual": false, + "name": "Divine Magic", + "params": { + "spell_list": "warden" + }, + "prose": "See Spells for full details on divine magic.\nHoly symbol: A cleric must carry a holy symbol (see Adventuring Gear).\nDeity disfavour: Clerics must be faithful to the tenets of their alignment, clergy, and religion. Clerics who fall from favour with their deity may incur penalties.\nMagical research: A cleric of any level may spend time and money on magical research. This allows them to create new spells or other magical effects associated with their deity. When a cleric reaches 9th level, they are also able to create magic items.\nSpell casting: Once a cleric has proven their faith (from 2nd level), the character may pray to receive spells. The level progression table (below) shows the number of spells a cleric may memorize, based on their experience level. The list of spells available to clerics is found in Cleric Spells.\nUsing magic items: As spell casters, clerics can use magic scrolls of spells on their spell list. They can also use items that may only be used by divine spell casters (e.g. some magic staves).", + "tag": "divine_magic" + }, + { + "manual": false, + "name": "Turning the Undead", + "params": {}, + "prose": "Clerics can invoke the power of their deity to repel undead monsters encountered. To turn the undead, the player rolls 2d6. The referee then consults the table below, comparing the roll against the HD of the type of undead monsters targeted.", + "tag": "turn_undead" + } + ], + "armour": { + "kind": "any", + "shields_allowed": true + }, + "hit_die": 6, + "id": "warden", + "languages": [ + "common" + ], + "level_titles": [ + "Acolyte", + "Adept", + "Priest(ess)", + "Vicar", + "Curate", + "Elder", + "Bishop", + "Lama", + "Matriarch (Patriarch)" + ], + "max_level": 14, + "may_not_lower": [], + "name": "Warden", + "overrides_applied": [], + "prime_requisites": [ + "wis" + ], + "progression": [ + { + "attack_bonus": 0, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 1, + "die": 6 + }, + "level": 1, + "saves": { + "breath": 16, + "death": 11, + "paralysis": 14, + "spells": 15, + "wands": 12 + }, + "spell_slots": [ + 0, + 0, + 0, + 0, + 0 + ], + "thac0": 19, + "xp": 0 + }, + { + "attack_bonus": 0, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 2, + "die": 6 + }, + "level": 2, + "saves": { + "breath": 16, + "death": 11, + "paralysis": 14, + "spells": 15, + "wands": 12 + }, + "spell_slots": [ + 1, + 0, + 0, + 0, + 0 + ], + "thac0": 19, + "xp": 1500 + }, + { + "attack_bonus": 0, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 3, + "die": 6 + }, + "level": 3, + "saves": { + "breath": 16, + "death": 11, + "paralysis": 14, + "spells": 15, + "wands": 12 + }, + "spell_slots": [ + 2, + 0, + 0, + 0, + 0 + ], + "thac0": 19, + "xp": 3000 + }, + { + "attack_bonus": 0, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 4, + "die": 6 + }, + "level": 4, + "saves": { + "breath": 16, + "death": 11, + "paralysis": 14, + "spells": 15, + "wands": 12 + }, + "spell_slots": [ + 2, + 1, + 0, + 0, + 0 + ], + "thac0": 19, + "xp": 6000 + }, + { + "attack_bonus": 2, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 5, + "die": 6 + }, + "level": 5, + "saves": { + "breath": 14, + "death": 9, + "paralysis": 12, + "spells": 12, + "wands": 10 + }, + "spell_slots": [ + 2, + 2, + 0, + 0, + 0 + ], + "thac0": 17, + "xp": 12000 + }, + { + "attack_bonus": 2, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 6, + "die": 6 + }, + "level": 6, + "saves": { + "breath": 14, + "death": 9, + "paralysis": 12, + "spells": 12, + "wands": 10 + }, + "spell_slots": [ + 2, + 2, + 1, + 1, + 0 + ], + "thac0": 17, + "xp": 25000 + }, + { + "attack_bonus": 2, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 7, + "die": 6 + }, + "level": 7, + "saves": { + "breath": 14, + "death": 9, + "paralysis": 12, + "spells": 12, + "wands": 10 + }, + "spell_slots": [ + 2, + 2, + 2, + 1, + 1 + ], + "thac0": 17, + "xp": 50000 + }, + { + "attack_bonus": 2, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 8, + "die": 6 + }, + "level": 8, + "saves": { + "breath": 14, + "death": 9, + "paralysis": 12, + "spells": 12, + "wands": 10 + }, + "spell_slots": [ + 3, + 3, + 2, + 2, + 1 + ], + "thac0": 17, + "xp": 100000 + }, + { + "attack_bonus": 5, + "hit_dice": { + "bonus": 0, + "con_applies": true, + "count": 9, + "die": 6 + }, + "level": 9, + "saves": { + "breath": 11, + "death": 6, + "paralysis": 9, + "spells": 9, + "wands": 7 + }, + "spell_slots": [ + 3, + 3, + 3, + 2, + 2 + ], + "thac0": 14, + "xp": 200000 + }, + { + "attack_bonus": 5, + "hit_dice": { + "bonus": 1, + "con_applies": false, + "count": 9, + "die": 6 + }, + "level": 10, + "saves": { + "breath": 11, + "death": 6, + "paralysis": 9, + "spells": 9, + "wands": 7 + }, + "spell_slots": [ + 4, + 4, + 3, + 3, + 2 + ], + "thac0": 14, + "xp": 300000 + }, + { + "attack_bonus": 5, + "hit_dice": { + "bonus": 2, + "con_applies": false, + "count": 9, + "die": 6 + }, + "level": 11, + "saves": { + "breath": 11, + "death": 6, + "paralysis": 9, + "spells": 9, + "wands": 7 + }, + "spell_slots": [ + 4, + 4, + 4, + 3, + 3 + ], + "thac0": 14, + "xp": 400000 + }, + { + "attack_bonus": 5, + "hit_dice": { + "bonus": 3, + "con_applies": false, + "count": 9, + "die": 6 + }, + "level": 12, + "saves": { + "breath": 11, + "death": 6, + "paralysis": 9, + "spells": 9, + "wands": 7 + }, + "spell_slots": [ + 5, + 5, + 4, + 4, + 3 + ], + "thac0": 14, + "xp": 500000 + }, + { + "attack_bonus": 7, + "hit_dice": { + "bonus": 4, + "con_applies": false, + "count": 9, + "die": 6 + }, + "level": 13, + "saves": { + "breath": 8, + "death": 3, + "paralysis": 7, + "spells": 7, + "wands": 5 + }, + "spell_slots": [ + 5, + 5, + 5, + 4, + 4 + ], + "thac0": 12, + "xp": 600000 + }, + { + "attack_bonus": 7, + "hit_dice": { + "bonus": 5, + "con_applies": false, + "count": 9, + "die": 6 + }, + "level": 14, + "saves": { + "breath": 8, + "death": 3, + "paralysis": 7, + "spells": 7, + "wands": 5 + }, + "spell_slots": [ + 6, + 5, + 5, + 5, + 4 + ], + "thac0": 12, + "xp": 700000 + } + ], + "race": "human", + "requirements": {}, + "thief_skills": [], + "weapons": { + "kind": "allowed", + "manual_notes": [], + "weapon_ids": [ + "club", + "mace", + "sling", + "staff", + "war_hammer" + ] + }, + "xp_tiers": [ + { + "minimums": { + "wis": 16 + }, + "modifier_pct": 10 + }, + { + "minimums": { + "wis": 13 + }, + "modifier_pct": 5 + }, + { + "minimums": { + "wis": 9 + }, + "modifier_pct": 0 + }, + { + "minimums": { + "wis": 6 + }, + "modifier_pct": -10 + }, + { + "minimums": { + "wis": 3 + }, + "modifier_pct": -20 + } + ] + }, + "extra_languages": [], + "id": "character-0010", + "inventory": { + "items": [], + "purse": { + "cp": 0, + "ep": 0, + "gp": 0, + "pp": 0, + "sp": 0 + }, + "rings": [], + "shield": null, + "valuables": [], + "wielded": [], + "worn_armour": null + }, + "level": 2, + "max_hp": 400, + "memorized_spells": [], + "name": "Bryn", + "nonregen_damage": 0, + "race": "human", + "scores": { + "cha": 10, + "con": 10, + "dex": 10, + "int": 10, + "str": 10, + "wis": 10 + }, + "spell_book": [], + "stat_modifiers": [], + "xp": 1500 + } + ] + }, + "quests": {}, + "rng_streams": { + "effects": { + "inc": 110921974297112361420962594425958014099, + "state": 323578275112908533770403587567316273018 + } + }, + "ruleset": { + "aoe_friendly_fire": true, + "back_stab_needs_both_skills": true, + "deprivation_penalties": false, + "encumbrance": "basic", + "failed_trap_removal_springs": true, + "formation_width_limit": true, + "hd5_counts_as_magical": false, + "hp_reroll_at_first_level": false, + "individual_initiative": false, + "magic_item_death_save": true, + "thac0_arithmetic": false, + "variable_weapon_damage": true, + "weapon_reload": false, + "xp_award_timing": "on_return" + }, + "treasure_snapshot_cp": null + }, + "schema_version": 4 +} diff --git a/tests/test_view_spell_lists.py b/tests/test_view_spell_lists.py new file mode 100644 index 0000000..f1ef224 --- /dev/null +++ b/tests/test_view_spell_lists.py @@ -0,0 +1,623 @@ +"""The player view lists the spells each caster may prepare or learn (issue #326). + +A remote front end builds its prepare and learn dialogs from `PlayerView` alone. Before, the view named a spell +only once a member had it in a spell book, memorized, or running as an effect, so a player couldn't find out +that the adventure bundles a spell their cleric may pray for or their magic-user may learn. +`MemberView.preparable_spells` and `MemberView.learnable_spells` list what `PrepareSpells` and `LearnSpell` +accept for the member, `MemberView.spell_slots` gives the slots to fit them in, and `PlayerView.spell_names`, +`PlayerView.reversed_spell_names`, and `PlayerView.spell_levels` name and level every one of them. + +The rules are the OSE SRD's. Rules of Magic, for a divine caster: "When praying for spells, divine spell casters +may choose any spells in their class’ spell list that they are of high enough level to cast." For an arcane +caster: "Arcane spell casters memorize spells by studying spell books (see Spell Books) and are thus limited to +choosing from the spells in their spell book." Spell Books: "A character’s spell book contains exactly the number +of spells that the character is capable of memorizing", and when that number increases, "the number of spells in +the spell book may be brought in line with the number of spells the character can memorize." So neither list +holds a spell of a level the member has no slot for, and neither command accepts one. +""" + +import json +from collections.abc import Callable +from pathlib import Path + +import pytest + +import positions_fixtures as pf +from osrlib.core.abilities import AbilityScore +from osrlib.core.character import Character +from osrlib.core.classes import ClassDefinition +from osrlib.core.effects import Condition, grant_condition +from osrlib.core.events import Visibility +from osrlib.core.items import MagicItemInstance +from osrlib.core.spells import MemorizedSpell, SpellTemplate +from osrlib.crawl.adventure import Adventure +from osrlib.crawl.commands import AwardXP, Command, EnterDungeon, LearnSpell, PrepareSpells, Rest, SpawnMonsters +from osrlib.crawl.party import Party +from osrlib.crawl.session import GameSession +from osrlib.crawl.views import MemberView, PlayerView +from osrlib.data import load_classes, load_spells +from osrlib.persistence import load_game, save_game + +SAVE_2_7_0 = Path(__file__).parent / "saves" / "view_spell_lists_2.7.0.json" +"""A save of `casters()` after a night's rest, written by osrlib 2.7.0 before the lists existed.""" + +# The built-in spell lists, from the OSE SRD's Cleric Spells and Magic-User Spells pages, in id order, which is +# the built-in catalog's order. +CLERIC_1 = ( + "cure_light_wounds", + "detect_evil_c", + "detect_magic_c", + "light_c", + "protection_from_evil_c", + "purify_food_and_water", + "remove_fear", + "resist_cold", +) +CLERIC_2 = ( + "bless", + "find_traps", + "hold_person_c", + "know_alignment", + "resist_fire", + "silence_15_radius", + "snake_charm", + "speak_with_animals", +) +MAGIC_USER_2 = ( + "continual_light_mu", + "detect_evil_mu", + "detect_invisible", + "esp", + "invisibility", + "knock", + "levitate", + "locate_object_mu", + "mirror_image", + "phantasmal_force", + "web", + "wizard_lock", +) + +PREPARE_SPELL_CODES = { + "magic.memorize.not_a_caster", + "magic.memorize.unknown_spell", + "magic.memorize.wrong_list", + "magic.memorize.not_in_book", + "magic.memorize.slots_exceeded", +} +"""The codes by which `PrepareSpells` refuses one plain copy of a spell for a reason of the spell and the member.""" + +LEARN_SPELL_CODES = { + "magic.book.not_arcane", + "magic.book.unknown_spell", + "magic.book.wrong_list", + "magic.book.duplicate", + "magic.book.capacity_exceeded", +} +"""The codes by which `LearnSpell` refuses a spell for a reason of the spell and the member.""" + + +# ---------------------------------------------------------------------- the adventure's spells + + +def bundled(base_id: str, spell_id: str, **changes) -> SpellTemplate: + """A built-in spell under a new id and name, with `changes` applied, as an adventure bundles it.""" + document = { + **load_spells().get(base_id).model_dump(), + "id": spell_id, + "name": spell_id.replace("_", " ").title(), + **changes, + } + return SpellTemplate.model_validate(document) + + +def _balm() -> SpellTemplate: + document = bundled("cure_light_wounds", "balm").model_dump() + document["reversed_form"] = {**document["reversed_form"], "name": "Bane"} + return SpellTemplate.model_validate(document) + + +BALM = _balm() +"""A 1st-level cleric spell that reverses, as the issue's repro bundles it.""" +SANCTUM = bundled("remove_curse_c", "sanctum") +"""A 3rd-level cleric spell. No cleric in the party has a 3rd-level slot.""" +GLIMMER = bundled("shield", "glimmer") +"""A 1st-level magic-user spell. Every magic-user and elf in the party has a full book at 1st level.""" +MIRE = bundled("web", "mire") +"""A 2nd-level magic-user spell, which a magic-user with room at 2nd level may learn.""" +MEND_WOUNDS = bundled("cure_light_wounds", "mend_wounds", spell_list="warden") +"""A 1st-level spell on the warden's own list.""" +WARD_OF_AGES = bundled("bless", "ward_of_ages", spell_list="warden") +"""A 2nd-level spell on the warden's list. A 2nd-level warden has no 2nd-level slot.""" +HEX = bundled("sleep", "hex", spell_list="witch") +"""A spell on a list no party member uses, like one only the adventure's monsters cast.""" + +SPELLS = (BALM, SANCTUM, GLIMMER, MIRE, MEND_WOUNDS, WARD_OF_AGES, HEX) +HIDDEN = ("sanctum", "glimmer", "ward_of_ages", "hex") + + +def adventure(*spells: SpellTemplate) -> Adventure: + base = pf.corridor() + return Adventure.model_validate({**base.model_dump(), "spells": [spell.model_dump() for spell in spells]}) + + +def _warden() -> ClassDefinition: + """A divine class of your own that casts from its own list, with the cleric's progression.""" + document = load_classes().get("cleric").model_dump(mode="json") + document.update(id="warden", name="Warden") + document["abilities"] = [ + {**ability, "params": {"spell_list": "warden"}} if ability["tag"] == "divine_magic" else ability + for ability in document["abilities"] + ] + return ClassDefinition.model_validate(document) + + +WARDEN = _warden() + + +# ---------------------------------------------------------------------- the party + + +def member(name: str, class_id: str, level: int, *book: str) -> Character: + """A built-in-class character at `level`, with `book` as the spell book.""" + return Character.model_validate({**pf.character(name, class_id, level=level).model_dump(), "spell_book": book}) + + +def warden(name: str, level: int) -> Character: + return Character( + name=name, + class_id="warden", + custom_class=WARDEN, + race="human", + level=level, + xp=WARDEN.row(level).xp, + scores={ability: 10 for ability in AbilityScore}, + alignment="lawful", + max_hp=400, + current_hp=400, + ) + + +def party() -> Party: + """Casters of every kind beside two who cast nothing. + + - Hild, a 3rd-level fighter, and Nim, a 3rd-level thief, cast nothing. + - Aelin, a 1st-level elf, has one 1st-level slot, and her book's one spell fills it. + - Wren, a 3rd-level magic-user, has two 1st-level slots and one 2nd-level slot. Her book fills the 1st level + and has nothing at the 2nd. *Light* reverses into *darkness*. + - Sefa, a 1st-level magic-user drained from a higher level, has one 1st-level slot and a book that still holds + *web*, a 2nd-level spell. + - Ivo, a 3rd-level magic-user, has a book with *frost dart*, a spell from another adventure that this session's + catalog doesn't have. + - Tam, a 1st-level cleric, has no slots. + - Oswin, a 2nd-level cleric, has one 1st-level slot. + - Mara, a 4th-level cleric, has two 1st-level slots and one 2nd-level slot. + - Bryn, a 2nd-level warden, has the cleric's slots and casts from the warden's list. + """ + return Party( + members=[ + member("Hild", "fighter", 3), + member("Nim", "thief", 3), + member("Aelin", "elf", 1, "sleep"), + member("Wren", "magic_user", 3, "magic_missile", "light_mu"), + member("Sefa", "magic_user", 1, "sleep", "web"), + member("Ivo", "magic_user", 3, "frost_dart", "sleep"), + member("Tam", "cleric", 1), + member("Oswin", "cleric", 2), + member("Mara", "cleric", 4), + warden("Bryn", 2), + ] + ) + + +def casters(*, rested: bool = True) -> GameSession: + """The party in town with every spell in `SPELLS` bundled, after a night's rest unless `rested` is false.""" + game = GameSession.new(party(), adventure(*SPELLS), seed=7) + if rested: + assert game.execute(Rest(kind="night")).accepted + return game + + +EXPECTED = { + "Hild": {"preparable": (), "learnable": (), "slots": ()}, + "Nim": {"preparable": (), "learnable": (), "slots": ()}, + # The book's spell is the one 1st-level spell, so the book is full at the only level with a slot. + "Aelin": {"preparable": ("sleep",), "learnable": (), "slots": (1, 0, 0, 0, 0)}, + # Catalog order, so *light* comes before *magic missile* although the book has them the other way round. + # The 1st level is full, so only the 2nd-level spells can be learned: the built-in ones, then the bundled one. + "Wren": { + "preparable": ("light_mu", "magic_missile"), + "learnable": (*MAGIC_USER_2, "mire"), + "slots": (2, 1, 0, 0, 0, 0), + }, + # *Web* stays in the book but takes no slot at 1st level, and the book is full at the 1st. + "Sefa": {"preparable": ("sleep",), "learnable": (), "slots": (1, 0, 0, 0, 0, 0)}, + # `LearnSpell` refuses every spell while the book holds one the catalog lacks (`magic.book.unknown_spell`), + # and `PrepareSpells` refuses *frost dart* alone. + "Ivo": {"preparable": ("sleep",), "learnable": (), "slots": (2, 1, 0, 0, 0, 0)}, + "Tam": {"preparable": (), "learnable": (), "slots": (0, 0, 0, 0, 0)}, + "Oswin": {"preparable": (*CLERIC_1, "balm"), "learnable": (), "slots": (1, 0, 0, 0, 0)}, + "Mara": {"preparable": (*sorted(CLERIC_1 + CLERIC_2), "balm"), "learnable": (), "slots": (2, 1, 0, 0, 0)}, + "Bryn": {"preparable": ("mend_wounds",), "learnable": (), "slots": (1, 0, 0, 0, 0)}, +} + + +def _player_view(game: GameSession) -> PlayerView: + view = game.view(Visibility.PLAYER) + assert isinstance(view, PlayerView) + return view + + +def _sheet(view: PlayerView, name: str) -> MemberView: + return next(sheet for sheet in view.party if sheet.name == name) + + +def _lists(view: PlayerView) -> dict[str, tuple[tuple[str, ...], tuple[str, ...], tuple[int, ...]]]: + return {sheet.name: (sheet.preparable_spells, sheet.learnable_spells, sheet.spell_slots) for sheet in view.party} + + +# ---------------------------------------------------------------------- what each member may choose + + +@pytest.mark.parametrize("name", list(EXPECTED)) +def test_each_member_lists_the_spells_they_may_prepare_and_learn(name): + sheet = _sheet(_player_view(casters()), name) + + expected = EXPECTED[name] + assert sheet.preparable_spells == expected["preparable"] + assert sheet.learnable_spells == expected["learnable"] + assert sheet.spell_slots == expected["slots"] + + +def _probe( + make: Callable[[], GameSession], name: str, command: Callable[[str, str], Command], codes: set[str] +) -> set[str]: + """The ids the command accepts for the member, checking that every refusal is for the spell and the member. + + A refused command changes nothing, so the probes share a session until one is accepted, and then a fresh one + is made, because an accepted preparation or learning changes what the next probe sees. + """ + game = make() + probes = sorted( + {spell.id for spell in game.effective_spells.spells} + | {spell_id for character in game.party.members for spell_id in character.spell_book} + | {"no_such_spell"} + ) + accepted: set[str] = set() + for spell_id in probes: + result = game.execute(command(pf.named(game, name), spell_id)) + if result.accepted: + accepted.add(spell_id) + game = make() + continue + refused = {rejection.code for rejection in result.rejections} + assert refused and refused <= codes, (name, spell_id, refused) + return accepted + + +def _prepare(character_id: str, spell_id: str) -> Command: + return PrepareSpells(character_id=character_id, selections=(MemorizedSpell(spell_id=spell_id),)) + + +def _learn(character_id: str, spell_id: str) -> Command: + return LearnSpell(character_id=character_id, spell_id=spell_id) + + +@pytest.mark.parametrize("name", list(EXPECTED)) +def test_a_spell_is_preparable_exactly_when_prepare_spells_accepts_it(name): + """Every spell id the session knows, every id in a book, and one id nobody has, prepared one plain copy at a time. + + The party has slept, is in town, and can act, so the command refuses only for the spell and the member. + """ + sheet = _sheet(_player_view(casters()), name) + + accepted = _probe(casters, name, _prepare, PREPARE_SPELL_CODES) + + assert set(sheet.preparable_spells) == accepted + assert len(sheet.preparable_spells) == len(accepted) + + +@pytest.mark.parametrize("name", list(EXPECTED)) +def test_a_spell_is_learnable_exactly_when_learn_spell_accepts_it(name): + sheet = _sheet(_player_view(casters()), name) + + accepted = _probe(casters, name, _learn, LEARN_SPELL_CODES) + + assert set(sheet.learnable_spells) == accepted + assert len(sheet.learnable_spells) == len(accepted) + + +def test_an_arcane_caster_may_prepare_the_reverse_of_a_listed_spell_that_has_one(): + """*Light* reverses into *darkness*, and *magic missile* doesn't reverse (`magic.memorize.not_reversible`).""" + game = casters() + view = _player_view(game) + wren = _sheet(view, "Wren") + + assert wren.preparable_spells == ("light_mu", "magic_missile") + assert view.reversed_spell_names["light_mu"] == "Darkness" + assert "magic_missile" not in view.reversed_spell_names + darkness = PrepareSpells(character_id=wren.id, selections=(MemorizedSpell(spell_id="light_mu", reversed=True),)) + assert game.execute(darkness).accepted + refused = casters().execute( + PrepareSpells(character_id=wren.id, selections=(MemorizedSpell(spell_id="magic_missile", reversed=True),)) + ) + assert [rejection.code for rejection in refused.rejections] == ["magic.memorize.not_reversible"] + + +def test_a_selection_that_fills_every_slot_from_the_lists_is_accepted(): + """Mara fills her two 1st-level slots and her one 2nd-level slot from her list, counted by `spell_levels`.""" + game = casters() + view = _player_view(game) + mara = _sheet(view, "Mara") + picks: list[str] = [] + for spell_level, slots in enumerate(mara.spell_slots, start=1): + at_level = [spell_id for spell_id in mara.preparable_spells if view.spell_levels[spell_id] == spell_level] + picks.extend(at_level[:slots]) + + assert picks == ["cure_light_wounds", "detect_evil_c", "bless"] + selections = tuple(MemorizedSpell(spell_id=spell_id) for spell_id in picks) + assert game.execute(PrepareSpells(character_id=mara.id, selections=selections)).accepted + + +# ---------------------------------------------------------------------- the moment doesn't change the lists + + +def test_the_lists_are_the_same_before_the_party_has_slept(): + """`PrepareSpells` refuses with `magic.memorize.needs_sleep`, which is about the moment, not the spell.""" + game = casters(rested=False) + oswin = pf.named(game, "Oswin") + + refused = game.execute(_prepare(oswin, "balm")) + + assert [rejection.code for rejection in refused.rejections] == ["magic.memorize.needs_sleep"] + assert _lists(_player_view(game)) == _lists(_player_view(casters())) + assert _sheet(_player_view(game), "Oswin").preparable_spells == EXPECTED["Oswin"]["preparable"] + + +def test_the_lists_are_the_same_during_an_encounter(): + """Both commands refuse with `session.command.wrong_mode` while monsters are in sight.""" + game = casters() + rested = _lists(_player_view(game)) + assert game.execute(EnterDungeon(dungeon_id="crypt")).accepted + assert game.execute(SpawnMonsters(template_id="goblin", count_fixed=1, distance_feet=60)).accepted + assert game.mode.value in ("encounter", "battle") + + oswin, wren = pf.named(game, "Oswin"), pf.named(game, "Wren") + for refused in (game.execute(_prepare(oswin, "balm")), game.execute(_learn(wren, "mire"))): + assert [rejection.code for rejection in refused.rejections] == ["session.command.wrong_mode"] + assert _lists(_player_view(game)) == rested + assert "balm" in _sheet(_player_view(game), "Oswin").preparable_spells + + +def test_the_lists_are_the_same_while_the_member_cant_act(): + """An asleep cleric and an asleep magic-user are refused with `session.command.member_incapacitated`.""" + game = casters() + rested = _lists(_player_view(game)) + for name in ("Oswin", "Wren"): + grant_condition(game.member(pf.named(game, name)), Condition.ASLEEP, None) + + oswin, wren = pf.named(game, "Oswin"), pf.named(game, "Wren") + for refused in (game.execute(_prepare(oswin, "balm")), game.execute(_learn(wren, "mire"))): + assert [rejection.code for rejection in refused.rejections] == ["session.command.member_incapacitated"] + assert _lists(_player_view(game)) == rested + assert "mire" in _sheet(_player_view(game), "Wren").learnable_spells + + +# ---------------------------------------------------------------------- the lists follow the member + + +def test_the_issues_cleric_sees_the_bundled_spell_at_second_level(): + """The issue's repro: a 1st-level cleric awarded 2,500 XP reaches 2nd level, which has one 1st-level slot.""" + game = GameSession.new(Party(members=[member("Tam", "cleric", 1)]), adventure(BALM), seed=7) + tam = pf.named(game, "Tam") + first = _player_view(game) + assert _sheet(first, "Tam").preparable_spells == () + assert "balm" not in first.spell_names + + assert game.execute(AwardXP(character_id=tam, amount=2500)).accepted + assert game.execute(Rest(kind="night")).accepted + view = _player_view(game) + + assert _sheet(view, "Tam").level == 2 + assert _sheet(view, "Tam").preparable_spells == (*CLERIC_1, "balm") + assert (view.spell_names["balm"], view.spell_levels["balm"], view.reversed_spell_names["balm"]) == ( + "Balm", + 1, + "Bane", + ) + assert game.execute(_prepare(tam, "balm")).accepted + + +def test_a_cleric_who_gains_a_spell_level_lists_its_spells(): + """A 3rd-level cleric has two 1st-level slots. 3,000 XP more makes 6,000 and 4th level, with a 2nd-level slot.""" + game = GameSession.new(Party(members=[member("Mara", "cleric", 3)]), adventure(BALM, SANCTUM), seed=7) + mara = pf.named(game, "Mara") + before = _player_view(game) + assert _sheet(before, "Mara").preparable_spells == (*CLERIC_1, "balm") + assert "bless" not in before.spell_names + + assert game.execute(AwardXP(character_id=mara, amount=3000)).accepted + after = _player_view(game) + + sheet = _sheet(after, "Mara") + assert (sheet.level, sheet.spell_slots) == (4, (2, 1, 0, 0, 0)) + assert sheet.preparable_spells == (*sorted(CLERIC_1 + CLERIC_2), "balm") + assert after.spell_levels["bless"] == 2 + assert "sanctum" not in after.spell_names + + +def test_learning_a_spell_moves_it_from_learnable_to_preparable(): + """Wren's one 2nd-level slot gives her book room for one 2nd-level spell, so learning *mire* fills it.""" + game = casters() + wren = pf.named(game, "Wren") + + assert game.execute(_learn(wren, "mire")).accepted + sheet = _sheet(_player_view(game), "Wren") + + assert sheet.spell_book == ("magic_missile", "light_mu", "mire") + assert sheet.preparable_spells == ("light_mu", "magic_missile", "mire") + assert sheet.learnable_spells == () + + +# ---------------------------------------------------------------------- names, reverses, and levels + + +def test_every_listed_spell_is_named_and_levelled_from_the_sessions_catalog(): + game = casters() + view = _player_view(game) + catalog = game.effective_spells + listed = { + spell_id for expected in EXPECTED.values() for spell_id in (*expected["preparable"], *expected["learnable"]) + } + + assert listed <= set(view.spell_names) + for spell_id in listed: + spell = catalog.get(spell_id) + assert view.spell_names[spell_id] == spell.name + assert view.spell_levels[spell_id] == spell.level + if spell.reversed_form is not None: + assert view.reversed_spell_names[spell_id] == spell.reversed_form.name + else: + assert spell_id not in view.reversed_spell_names + assert (view.spell_names["mend_wounds"], view.spell_levels["mend_wounds"]) == ("Mend Wounds", 1) + assert (view.spell_names["mire"], view.spell_levels["mire"]) == ("Mire", 2) + + +def test_spell_levels_has_a_level_for_every_named_spell(): + """Sefa's *web* is in her book with no slot to take, so it's named and levelled, not listed.""" + view = _player_view(casters()) + + assert view.spell_levels + assert set(view.spell_levels) == set(view.spell_names) + assert view.spell_levels["web"] == 2 + assert "web" not in _sheet(view, "Sefa").preparable_spells + assert (view.spell_levels["sleep"], view.spell_levels["light_mu"], view.spell_levels["bless"]) == (1, 1, 2) + + +def test_the_view_names_exactly_the_spells_it_shows(): + """The names come from the books, the memorized copies, the effects, and the two lists, and nowhere else.""" + view = _player_view(casters()) + shown = { + spell_id + for sheet in view.party + for spell_id in ( + *sheet.spell_book, + *(copy["spell_id"] for copy in sheet.memorized_spells), + *sheet.preparable_spells, + *sheet.learnable_spells, + ) + } | {effect.kind for effect in view.effects} + + # *Frost dart* is in Ivo's book, and this session's catalog doesn't have it. + assert set(view.spell_names) == shown - {"frost_dart"} + # Mara's two cleric levels, Wren's 2nd-level choices, the bundled spells someone may choose, and the books' own + # spells. Sefa's *web* is one of the 2nd-level magic-user spells. + assert set(view.spell_names) == { + *CLERIC_1, + *CLERIC_2, + *MAGIC_USER_2, + "balm", + "mend_wounds", + "mire", + "sleep", + "magic_missile", + "light_mu", + } + + +def test_a_spell_no_member_may_choose_stays_hidden(): + """A bundled spell above every member's slots, at a full book's level, or on a list nobody uses isn't named.""" + view = _player_view(casters()) + blob = view.model_dump_json() + + for spell_id in HIDDEN: + assert spell_id not in view.spell_names + assert f'"{spell_id}"' not in blob + for name in ("Sanctum", "Glimmer", "Ward Of Ages", "Hex"): + assert name not in blob + + +def test_a_spell_on_a_scroll_appears_only_when_a_member_may_learn_it_anyway(): + """A scroll adds nothing to either list, because the OSE SRD adds a spell to a book by mentoring or research. + + Wren's book has room at the 2nd level and none at the 1st, so the scroll's *web* is listed because any + 2nd-level magic-user spell is, while its *sleep* and its 3rd-level *fire ball* stay hidden. + """ + game = casters() + wren = game.member(pf.named(game, "Wren")) + wren.inventory.items.append( + MagicItemInstance( + instance_id="magic-item-9001", + template_id="spell_scroll_3", + identified=True, + state={"spell_list": "magic_user", "spells": ("hold_portal", "web", "fire_ball")}, + ) + ) + view = _player_view(game) + + assert "web" in _sheet(view, "Wren").learnable_spells + assert "hold_portal" not in view.spell_names + assert "fire_ball" not in view.spell_names + assert _lists(view) == _lists(_player_view(casters())) + + +# ---------------------------------------------------------------------- saves + + +def test_a_loaded_save_has_the_same_lists(): + game = casters() + + loaded = load_game(json.loads(json.dumps(save_game(game)))) + + view, reloaded = _player_view(game), _player_view(loaded) + assert _lists(reloaded) == _lists(view) + assert _sheet(reloaded, "Bryn").preparable_spells == ("mend_wounds",) + assert (reloaded.spell_names, reloaded.spell_levels) == (view.spell_names, view.spell_levels) + + +def test_a_save_from_osrlib_2_7_0_gives_the_lists(): + """The lists are worked out from the characters and the catalog, so a save from before they existed has them.""" + document = json.loads(SAVE_2_7_0.read_text()) + assert document["engine_version"] == "2.7.0" + + view = _player_view(load_game(document)) + + for name, expected in EXPECTED.items(): + sheet = _sheet(view, name) + assert (sheet.preparable_spells, sheet.learnable_spells, sheet.spell_slots) == ( + expected["preparable"], + expected["learnable"], + expected["slots"], + ) + assert view.spell_levels["balm"] == 1 + + +def test_a_player_view_from_before_the_lists_still_parses(): + """A client that kept a 2.7.0 player view's JSON reads it with every new field at its default.""" + document = json.loads(_player_view(casters()).model_dump_json()) + for sheet in document["party"]: + for field in ("preparable_spells", "learnable_spells", "spell_slots"): + sheet.pop(field) + document.pop("spell_levels") + + view = PlayerView.model_validate(document) + + assert view.spell_levels == {} + assert all( + (sheet.preparable_spells, sheet.learnable_spells, sheet.spell_slots) == ((), (), ()) for sheet in view.party + ) + + +# ---------------------------------------------------------------------- the docs + + +def test_the_views_guide_and_the_changelog_describe_the_lists(): + root = Path(__file__).parent.parent + guide = (root / "docs" / "guides" / "views-and-visibility.md").read_text() + changelog = (root / "CHANGELOG.md").read_text() + unreleased = changelog.split("## [Unreleased]", 1)[1].split("\n## [", 1)[0] + + for name in ("preparable_spells", "learnable_spells", "spell_slots", "spell_levels"): + assert name in guide, name + assert name in unreleased, name + assert "#326" in unreleased diff --git a/tests/test_view_spell_names.py b/tests/test_view_spell_names.py index dcdd182..23342c3 100644 --- a/tests/test_view_spell_names.py +++ b/tests/test_view_spell_names.py @@ -4,9 +4,17 @@ name with `load_spells()`, which lacks the spells an adventure bundles. `PlayerView.spell_names` carries the name of every spell id in the view, read from the session's catalog, and names nothing the view doesn't already show. + +Wren, the 3rd-level magic-user in these sessions, has two 1st-level slots and one 2nd-level slot. Where a test +pins her names exactly, her book is full at both levels, so the spells she may learn (issue #326) add none. +Oswin, the 3rd-level cleric, has two 1st-level slots and no 2nd-level slot. The OSE SRD lets a divine caster +"choose any spells in their class’ spell list that they are of high enough level to cast", so he may prepare +every 1st-level cleric spell, and the cleric tests name those beside the ones they pin. """ import positions_fixtures as pf +from osrlib.core.character import Character +from osrlib.core.effects import EffectDefinition from osrlib.core.events import Visibility from osrlib.core.items import MagicItemInstance from osrlib.core.spells import MemorizedSpell, SpellTemplate @@ -16,6 +24,7 @@ from osrlib.crawl.views import PlayerView from osrlib.data import load_spells from test_custom_spells import GLIMMER, adventure, custom_spell, prepare, session +from test_view_spell_lists import CLERIC_1, bundled, member # A cleric's spell of the adventure's own: protection from evil under a new id. Its effect # sets no kind of its own, so the effect's kind is the spell's id. @@ -38,6 +47,19 @@ def _player_view(game: GameSession) -> PlayerView: return view +def _names(*spells: str | SpellTemplate) -> dict[str, str]: + """The names a view should give: a built-in id's from `load_spells()`, a bundled spell's its own.""" + built_in = load_spells() + templates = (built_in.get(spell) if isinstance(spell, str) else spell for spell in spells) + return {spell.id: spell.name for spell in templates} + + +OSWINS_CHOICES = _names(*CLERIC_1) +"""What a 3rd-level cleric may prepare from the built-in catalog: every 1st-level cleric spell.""" +OSWINS_REVERSES = {"cure_light_wounds": "Cause Light Wounds", "light_c": "Darkness", "remove_fear": "Cause Fear"} +"""The reverses among the 1st-level cleric spells, as the OSE SRD names them.""" + + def _cleric_session(*spells) -> GameSession: # A 3rd-level cleric has two 1st-level spell slots and no spell book. party = Party(members=[pf.character("Hild", "fighter"), pf.character("Oswin", "cleric")]) @@ -60,7 +82,7 @@ def test_built_in_spells_in_the_book_and_memorized_have_their_names(): A reversed copy of *light* casts *darkness*, and its entry here is the spell's own name, "Light", because `spell_names` always names the normal form. `reversed_spell_names` has "Darkness". """ - game = session(book=("magic_missile", "sleep", "light_mu")) + game = session(book=("magic_missile", "sleep", "light_mu", "web")) wren = pf.named(game, "Wren") assert game.execute(Rest(kind="night")).accepted selections = (MemorizedSpell(spell_id="magic_missile"), MemorizedSpell(spell_id="light_mu", reversed=True)) @@ -68,26 +90,26 @@ def test_built_in_spells_in_the_book_and_memorized_have_their_names(): view = _player_view(game) - assert view.spell_names == {"magic_missile": "Magic Missile", "sleep": "Sleep", "light_mu": "Light"} + assert view.spell_names == {"magic_missile": "Magic Missile", "sleep": "Sleep", "light_mu": "Light", "web": "Web"} member = next(member for member in view.party if member.id == wren) assert member.memorized_spells[1] == {"spell_id": "light_mu", "reversed": True} def test_a_bundled_spell_under_a_new_id_has_the_name_the_adventure_gave_it(): """`load_spells()` has no "glimmer". The session's catalog does, and its name is "Glimmer".""" - game = session(GLIMMER, book=("glimmer", "magic_missile")) + game = session(GLIMMER, book=("glimmer", "magic_missile", "web")) assert prepare(game, "glimmer").accepted view = _player_view(game) - assert view.spell_names == {"glimmer": "Glimmer", "magic_missile": "Magic Missile"} + assert view.spell_names == {"glimmer": "Glimmer", "magic_missile": "Magic Missile", "web": "Web"} def test_a_member_with_no_spells_adds_no_names(): """The fighter beside the magic-user adds nothing, and a party of fighters has no spell names.""" - game = session(book=("sleep",)) + game = session(book=("sleep", "shield", "web")) - assert _player_view(game).spell_names == {"sleep": "Sleep"} + assert _player_view(game).spell_names == {"sleep": "Sleep", "shield": "Shield", "web": "Web"} fighters = Party(members=[pf.character("Hild", "fighter"), pf.character("Tam", "fighter")]) assert _player_view(GameSession.new(fighters, adventure(), seed=7)).spell_names == {} @@ -104,7 +126,54 @@ def test_a_spell_effect_is_named_after_the_cleric_has_spent_the_copy(): assert [(effect.character_id, effect.kind) for effect in view.effects] == [(oswin, "warding")] assert all(member.memorized_spells == () and member.spell_book == () for member in view.party) - assert view.spell_names == {"warding": "Warding"} + assert view.spell_names == OSWINS_CHOICES | _names(WARDING) + + +def _hex() -> SpellTemplate: + document = bundled("cure_light_wounds", "hex", spell_list="witch").model_dump() + document["reversed_form"] = {**document["reversed_form"], "name": "Unhex"} + return SpellTemplate.model_validate(document) + + +HEX = _hex() +"""A spell the adventure bundles on a list no party member casts from, like one only its monsters cast.""" + + +def test_a_spell_only_an_effect_shows_is_named_and_levelled(): + """A hex running on Hild is the one place its id appears: nobody may prepare or learn it, or holds it. + + Wren's book is full at both levels she has slots for, so it adds only its own spells. + """ + game = session(HEX, book=("magic_missile", "shield", "web")) + hild = pf.named(game, "Hild") + pf.attach(game, EffectDefinition(kind="hex"), hild) + + view = _player_view(game) + + assert [(effect.character_id, effect.kind) for effect in view.effects] == [(hild, "hex")] + assert view.spell_names == _names("magic_missile", "shield", "web") | {"hex": "Hex"} + assert view.reversed_spell_names == {"hex": "Unhex"} + assert view.spell_levels == {"magic_missile": 1, "shield": 1, "web": 2, "hex": 1} + + +def test_a_spell_held_without_a_slot_is_named_from_the_book_or_the_memorized_copy(): + """A spell a member holds but couldn't choose now is named because the book or the memorized copy shows it. + + Sefa, a 1st-level magic-user drained from a higher level, keeps *web* in her book with no 2nd-level slot, and + her one 1st-level slot is full. Tam, a 1st-level cleric brought in from another game, carries a copy of *bless* + memorized at a level he no longer has a slot for. Neither may prepare or learn either spell. + """ + tam = Character.model_validate( + {**member("Tam", "cleric", 1).model_dump(), "memorized_spells": [{"spell_id": "bless"}]} + ) + sefa = member("Sefa", "magic_user", 1, "sleep", "web") + game = GameSession.new(Party(members=[tam, sefa]), adventure(), seed=7) + + view = _player_view(game) + + assert view.spell_names == _names("sleep", "web", "bless") + assert view.reversed_spell_names == {"bless": "Blight"} + assert view.spell_levels == {"sleep": 1, "web": 2, "bless": 2} def test_an_effect_kind_that_isnt_a_spell_id_has_no_name(): @@ -117,7 +186,8 @@ def test_an_effect_kind_that_isnt_a_spell_id_has_no_name(): view = _player_view(game) assert [effect.kind for effect in view.effects] == ["light"] - assert view.spell_names == {"cure_light_wounds": "Cure Light Wounds"} + assert "light" not in view.spell_names + assert view.spell_names == OSWINS_CHOICES def test_a_spell_id_the_sessions_catalog_lacks_has_no_entry(): @@ -130,8 +200,11 @@ def test_a_spell_id_the_sessions_catalog_lacks_has_no_entry(): def test_the_spells_on_a_scroll_stay_hidden(): - """No spell on a scroll is named, identified or not, because the view shows no scroll's spells.""" - game = session(book=("magic_missile",)) + """No spell on a scroll is named, identified or not, because the view shows no scroll's spells. + + Wren's book is full at both levels she has slots for, so she can't learn the scrolls' spells either. + """ + game = session(book=("magic_missile", "shield", "invisibility")) wren = game.member(pf.named(game, "Wren")) wren.inventory.items.append( MagicItemInstance( @@ -151,7 +224,7 @@ def test_the_spells_on_a_scroll_stay_hidden(): view = _player_view(game) - assert view.spell_names == {"magic_missile": "Magic Missile"} + assert view.spell_names == {"magic_missile": "Magic Missile", "shield": "Shield", "invisibility": "Invisibility"} blob = view.model_dump_json() for hidden in ('"sleep"', '"Sleep"', '"web"', '"Web"', '"fire_ball"', '"Fire Ball"'): assert hidden not in blob @@ -162,7 +235,7 @@ def test_the_spells_on_a_scroll_stay_hidden(): def test_a_reversible_spell_in_a_book_has_its_reverses_name(): """*Light* reverses into *darkness*. The book holds `light_mu` and nothing is memorized.""" - game = session(book=("light_mu", "magic_missile")) + game = session(book=("light_mu", "magic_missile", "web")) view = _player_view(game) @@ -180,16 +253,16 @@ def test_a_clerics_unreversed_copy_still_has_its_reverses_name(): member = next(member for member in view.party if member.id == oswin) assert member.memorized_spells[0] == {"spell_id": "cure_light_wounds", "reversed": False} - assert view.reversed_spell_names == {"cure_light_wounds": "Cause Light Wounds"} + assert view.reversed_spell_names == OSWINS_REVERSES def test_a_spell_with_no_reverse_has_no_reverse_entry(): """*Magic missile* and *sleep* don't reverse, so neither has a reverse's name.""" - game = session(book=("magic_missile", "sleep")) + game = session(book=("magic_missile", "sleep", "web")) view = _player_view(game) - assert view.spell_names == {"magic_missile": "Magic Missile", "sleep": "Sleep"} + assert view.spell_names == {"magic_missile": "Magic Missile", "sleep": "Sleep", "web": "Web"} assert view.reversed_spell_names == {} @@ -200,5 +273,5 @@ def test_a_bundled_reversible_spell_has_the_reverses_name_the_adventure_gave_it( view = _player_view(game) - assert view.spell_names == {"mending": "Mending"} - assert view.reversed_spell_names == {"mending": "Rending"} + assert view.spell_names == OSWINS_CHOICES | {"mending": "Mending"} + assert view.reversed_spell_names == OSWINS_REVERSES | {"mending": "Rending"}