diff --git a/.ai/rules/characters.md b/.ai/rules/characters.md new file mode 100644 index 0000000..a05512e --- /dev/null +++ b/.ai/rules/characters.md @@ -0,0 +1,9 @@ +--- +paths: + - 'app/Livewire/Characters/**' +--- + +# Characters + +## The 5e sheet is a ruleset module: its own table, behind hasCharacterSheet(), storing only what the player decides +character_sheets is one row per character in its own table, never columns on entities, so one ruleset's shape stays off the core table. Ruleset::hasCharacterSheet() is the seam: Characters\Sheet aborts 404 without it, Entities\Show does not mount the card, and the API sets the relation only on such a campaign. Only what a player decides is stored (scores, proficiency lists, hit points, die, slots); modifiers, proficiency bonus, save and skill bonuses, passive Perception and initiative are methods on CharacterSheet that read App\Support\Sheets\FifthEdition, the pure maths class with the unit tests. Never store a derived number. The three lists and the slots are JSON on the row, the calendar's exception. Who writes is EntityPolicy::update(): a GM or the character's player; there is no sheet policy. The ability and skill names are SRD terms, so the card prints config('compendium.attribution'). diff --git a/.ai/rules/index.md b/.ai/rules/index.md index 3e7ccc1..22e2f09 100644 --- a/.ai/rules/index.md +++ b/.ai/rules/index.md @@ -14,6 +14,7 @@ Before planning or editing, find the row whose globs match the file's path and r | app/Calendar/**, app/Http/Controllers/CalendarFeedController.php, app/Mail/** | .ai/rules/calendar.md | | app/Livewire/Calendars/** | .ai/rules/calendars.md | | app/Actions/Campaigns/**, app/Actions/Campaigns/ExportCampaign.php | .ai/rules/campaigns.md | +| app/Livewire/Characters/** | .ai/rules/characters.md | | database/srd/**, app/Models/StatBlock.php, config/compendium.php, app/Console/Commands/ImportSrdCommand.php, app/Actions/Compendium/** | .ai/rules/commands.md | | config/broadcasting.php | .ai/rules/config.md | | resources/css/** | .ai/rules/css.md | diff --git a/README.md b/README.md index b7d7901..87a41dd 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ Slice 25 adds **downtime**, what each character did between sessions. A row is w Slice 26 adds **family trees**. A relationship may carry a kinship, parent, child, sibling, or spouse, read from the side it was written on, and the labels fill in from it when the GM leaves them blank. A character's page draws a "Family" card from the typed rows, two generations up and two down, walked through the relations card's own gate at both ends: a hidden row or a GM-only relative never reaches the party's tree, and the GM reads a mark on each. The kinship travels in the export and on both relation lists of the API. +Slice 27 adds **the 5e character sheet**, as a ruleset module. On a campaign on the SRD 5.2.1 rules a character's page carries a sheet: six ability scores, saving throw and skill proficiencies with expertise, hit points and hit dice, spell slots, armour class and speed, with every modifier, the proficiency bonus, every save and skill bonus, passive Perception and initiative computed from the scores and the level on every read and never stored. The character's player or a GM edits it, takes damage and healing on it, and presses "Long rest"; whoever may read the character reads it, and the party's pack from the ledger sits under it. The sheet lives in its own table behind `Ruleset::hasCharacterSheet()`, so a system-agnostic campaign never sees it, and it travels nested under its character in the export, the vault, and the API. + Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text. ## Local setup diff --git a/app/Actions/Campaigns/ExportCampaign.php b/app/Actions/Campaigns/ExportCampaign.php index 1fbdf6a..ceece55 100644 --- a/app/Actions/Campaigns/ExportCampaign.php +++ b/app/Actions/Campaigns/ExportCampaign.php @@ -5,6 +5,7 @@ use App\Models\Calendar; use App\Models\Campaign; use App\Models\CampaignMember; +use App\Models\CharacterSheet; use App\Models\Clock; use App\Models\Combatant; use App\Models\Decision; @@ -60,6 +61,7 @@ class ExportCampaign 'quest_objectives' => 'entities[].objectives', 'map_markers' => 'entities[].markers', 'entity_relations' => 'entities[].relations', + 'character_sheets' => 'entities[].sheet', 'scenes' => 'sessions[].scenes', 'secrets' => 'sessions[].secrets', 'game_session_entities' => 'sessions[].prepped', @@ -355,8 +357,12 @@ private function entities(Campaign $campaign): iterable ->withoutGlobalScopes() ->where('campaign_id', $campaign->id) ->whereNull('deleted_at') - ->with(['tags', 'viewers', 'media', 'objectives', 'markers', 'relations', 'statBlock']) + ->with(['tags', 'viewers', 'media', 'objectives', 'markers', 'relations', 'statBlock', 'sheet']) + // The id breaks a tie in created_at: PostgreSQL keeps timestamps to the + // second, and two pages made in one second otherwise come out in any + // order, which moved a media ordinal in CI once. ->orderBy('created_at') + ->orderBy('id') ->cursor() ->map(fn (Entity $entity) => [ 'id' => $entity->id, @@ -408,6 +414,9 @@ private function entities(Campaign $campaign): iterable 'player_visible' => $relation->player_visible, 'position' => $relation->position, ])->values()->all(), + // The ruleset's sheet, one-to-one with the character, so nested. Null + // for a character with none and for every other type. + 'sheet' => $this->sheet($entity->sheet), 'image' => $this->media($entity->getFirstMedia('image')), // A handout's attachments, in the same shape as the single image: the // facts about each file and a URL, never the bytes. The zip with the @@ -641,6 +650,43 @@ private function ledger(Campaign $campaign): iterable ]); } + /** + * The SRD 5.2.1 sheet as the row holds it: the scores, the three lists, the hit + * points, the die, and the slots. Nothing derived, because nothing derived is + * stored. + * + * @return array|null + */ + private function sheet(?CharacterSheet $sheet): ?array + { + if ($sheet === null) { + return null; + } + + return [ + 'strength' => $sheet->strength, + 'dexterity' => $sheet->dexterity, + 'constitution' => $sheet->constitution, + 'intelligence' => $sheet->intelligence, + 'wisdom' => $sheet->wisdom, + 'charisma' => $sheet->charisma, + 'saving_throws' => $sheet->saving_throws, + 'skills' => $sheet->skills, + 'expertise' => $sheet->expertise, + 'hp_max' => $sheet->hp_max, + 'hp_current' => $sheet->hp_current, + 'hp_temp' => $sheet->hp_temp, + 'hit_die' => $sheet->hit_die, + 'hit_dice_spent' => $sheet->hit_dice_spent, + // JSON has no integer keys, so the levels travel as strings and the + // reader turns them back. + 'spell_slots' => (object) array_map(fn (array $slot) => ['total' => $slot['total'], 'used' => $slot['used']], array_combine(array_map('strval', array_keys($sheet->slots())), $sheet->slots())), + 'spellcasting_ability' => $sheet->spellcasting_ability, + 'armor_class' => $sheet->armor_class, + 'speed' => $sheet->speed, + ]; + } + /** * @return iterable> A LazyCollection: it streams row by row. */ diff --git a/app/Actions/Campaigns/ImportCampaign.php b/app/Actions/Campaigns/ImportCampaign.php index e92f5fc..6e33364 100644 --- a/app/Actions/Campaigns/ImportCampaign.php +++ b/app/Actions/Campaigns/ImportCampaign.php @@ -393,6 +393,11 @@ private function children(array $document, IdMap $ids): void ]); } + // The ruleset's sheet, one-to-one, written after the character it belongs to. + if (($row['sheet'] ?? null) !== null) { + $entity->sheet()->create(['campaign_id' => $entity->campaign_id, ...$row['sheet']]); + } + foreach ($row['relations'] as $relation) { $entity->relations()->create([ 'campaign_id' => $entity->campaign_id, diff --git a/app/Actions/Campaigns/ReadCampaignFile.php b/app/Actions/Campaigns/ReadCampaignFile.php index 336cf61..4498d63 100644 --- a/app/Actions/Campaigns/ReadCampaignFile.php +++ b/app/Actions/Campaigns/ReadCampaignFile.php @@ -16,6 +16,7 @@ use App\Enums\Visibility; use App\Models\Calendar; use App\Models\Campaign; +use App\Models\CharacterSheet; use App\Models\Combatant; use App\Models\Decision; use App\Models\DowntimeActivity; @@ -30,6 +31,7 @@ use App\Support\Reckoning\GameDate; use App\Support\Reckoning\Reckoning; use App\Support\Reputation\Standing; +use App\Support\Sheets\FifthEdition; use BackedEnum; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; @@ -447,6 +449,7 @@ private function entities(array $rows): array 'objectives' => $this->objectives($row), 'markers' => $this->markers($row), 'relations' => $this->relations($row), + 'sheet' => $this->sheet($row), 'image' => $image, 'files' => $files, ]; @@ -545,6 +548,93 @@ private function relations(array $row): array return $relations; } + /** + * The SRD 5.2.1 sheet under a character, or null. Absent from a file older than + * slice 27, and null is what that means. A number outside the bounds is refused + * rather than clamped: a sheet is a player's own record, and a quiet clamp would + * hand them a different character. + * + * @param array $row + * @return array|null + */ + private function sheet(array $row): ?array + { + $sheet = $row['sheet'] ?? null; + + if (! is_array($sheet)) { + return null; + } + + $name = (string) ($row['name'] ?? 'a character'); + $parts = []; + + foreach (CharacterSheet::SCORE_COLUMNS as $column) { + $score = $this->integer($sheet, $column) ?? 10; + + if ($score < FifthEdition::MIN_SCORE || $score > FifthEdition::MAX_SCORE) { + $this->errors[] = "The sheet on \"{$name}\" has a {$column} of {$score}, which the rules do not allow."; + } + + $parts[$column] = $score; + } + + $abilities = array_keys(FifthEdition::ABILITIES); + $skills = array_keys(FifthEdition::SKILLS); + + $parts['saving_throws'] = $this->keyList($sheet, 'saving_throws', $abilities); + $parts['skills'] = $this->keyList($sheet, 'skills', $skills); + $parts['expertise'] = $this->keyList($sheet, 'expertise', $skills); + $parts['hp_max'] = max(0, min(FifthEdition::MAX_HIT_POINTS, $this->integer($sheet, 'hp_max') ?? 0)); + $parts['hp_current'] = max(0, min($parts['hp_max'], $this->integer($sheet, 'hp_current') ?? 0)); + $parts['hp_temp'] = max(0, min(FifthEdition::MAX_HIT_POINTS, $this->integer($sheet, 'hp_temp') ?? 0)); + $die = $this->integer($sheet, 'hit_die') ?? 8; + $parts['hit_die'] = in_array($die, FifthEdition::HIT_DICE, true) ? $die : 8; + $parts['hit_dice_spent'] = max(0, min(FifthEdition::MAX_LEVEL, $this->integer($sheet, 'hit_dice_spent') ?? 0)); + + $slots = []; + + foreach (is_array($sheet['spell_slots'] ?? null) ? $sheet['spell_slots'] : [] as $level => $slot) { + $level = (int) $level; + $total = is_array($slot) ? max(0, min(FifthEdition::MAX_SLOTS, (int) ($slot['total'] ?? 0))) : 0; + + if ($level >= 1 && $level <= FifthEdition::MAX_SLOT_LEVEL && $total > 0) { + $slots[$level] = ['total' => $total, 'used' => max(0, min($total, (int) ($slot['used'] ?? 0)))]; + } + } + + ksort($slots); + $parts['spell_slots'] = $slots; + + $ability = $this->text($sheet, 'spellcasting_ability', 3); + $parts['spellcasting_ability'] = in_array($ability, $abilities, true) ? $ability : null; + + $armor = $this->integer($sheet, 'armor_class'); + $parts['armor_class'] = $armor === null ? null : max(0, min(FifthEdition::MAX_ARMOR_CLASS, $armor)); + + $speed = $this->integer($sheet, 'speed'); + $parts['speed'] = $speed === null ? null : max(0, min(FifthEdition::MAX_SPEED, $speed)); + + return $parts; + } + + /** + * A list of keys, keeping only the ones the rules name. + * + * @param array $row + * @param list $allowed + * @return list + */ + private function keyList(array $row, string $key, array $allowed): array + { + $value = $row[$key] ?? []; + + if (! is_array($value)) { + return []; + } + + return array_values(array_unique(array_filter($value, fn ($item) => is_string($item) && in_array($item, $allowed, true)))); + } + /** * @param list> $rows * @return list> diff --git a/app/Actions/Campaigns/WriteCampaignMarkdown.php b/app/Actions/Campaigns/WriteCampaignMarkdown.php index 5e672f7..4ca4cf2 100644 --- a/app/Actions/Campaigns/WriteCampaignMarkdown.php +++ b/app/Actions/Campaigns/WriteCampaignMarkdown.php @@ -18,6 +18,7 @@ use App\Models\SessionRsvp; use App\Support\Reckoning\Reckoning; use App\Support\Reputation\Standing; +use App\Support\Sheets\FifthEdition; use Illuminate\Support\Collection; /** @@ -52,7 +53,7 @@ public function handle(Campaign $campaign): array $entities = Entity::withoutGlobalScopes() ->where('campaign_id', $campaign->id) ->whereNull('deleted_at') - ->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession', 'downtimeActivities.gameSession']) + ->with(['tags', 'parent', 'arc', 'player', 'objectives', 'relations.target', 'incomingRelations.source', 'reputationChanges.gameSession', 'downtimeActivities.gameSession', 'sheet']) ->orderBy('name') ->get(); @@ -243,6 +244,34 @@ private function entity(Entity $entity): string ->implode("\n"); } + // The ruleset's sheet: the scores with their modifiers, the hit points, the + // dice, the proficient skills with their bonuses, and the slots. Derived + // numbers are printed here because a vault page is read, not imported. + if ($entity->isCharacter() && $entity->sheet !== null) { + $sheet = $entity->sheet->setRelation('character', $entity); + $lines = []; + + foreach (FifthEdition::ABILITIES as $ability => $name) { + $lines[] = '- '.$name.' '.$sheet->score($ability).' ('.FifthEdition::signed($sheet->modifier($ability)).')'; + } + + $lines[] = '- Hit points: '.$sheet->hp_current.' of '.$sheet->hp_max.($sheet->hp_temp > 0 ? ' (+'.$sheet->hp_temp.' temporary)' : ''); + $lines[] = '- Hit dice: '.$sheet->hitDiceLeft().' of '.$sheet->hitDiceLabel(); + $lines[] = '- Proficiency bonus: '.FifthEdition::signed($sheet->proficiencyBonus()); + + foreach (FifthEdition::SKILLS as $key => $skill) { + if ($sheet->hasSkillProficiency($key) || $sheet->hasExpertise($key)) { + $lines[] = '- '.$skill['name'].' '.FifthEdition::signed($sheet->skillBonus($key)).($sheet->hasExpertise($key) ? ' (expertise)' : ''); + } + } + + foreach ($sheet->slots() as $level => $slot) { + $lines[] = '- Level '.$level.' slots: '.($slot['total'] - $slot['used']).' of '.$slot['total']; + } + + $body[] = "## Character sheet\n\n".implode("\n", $lines); + } + // What the character did between sessions, oldest first, with the days, the // range in the world when there is one, and the session it happened around. if ($entity->isCharacter() && $entity->downtimeActivities->isNotEmpty()) { diff --git a/app/Actions/Characters/AdjustHitPoints.php b/app/Actions/Characters/AdjustHitPoints.php new file mode 100644 index 0000000..cc3f7be --- /dev/null +++ b/app/Actions/Characters/AdjustHitPoints.php @@ -0,0 +1,35 @@ +hp_temp, $amount); + + $sheet->fill([ + 'hp_temp' => $sheet->hp_temp - $fromTemp, + 'hp_current' => max(0, $sheet->hp_current - ($amount - $fromTemp)), + ])->save(); + + return $sheet; + } + + public function heal(CharacterSheet $sheet, int $amount): CharacterSheet + { + $sheet->fill([ + 'hp_current' => min($sheet->hp_max, $sheet->hp_current + max(0, $amount)), + ])->save(); + + return $sheet; + } +} diff --git a/app/Actions/Characters/LongRest.php b/app/Actions/Characters/LongRest.php new file mode 100644 index 0000000..931a795 --- /dev/null +++ b/app/Actions/Characters/LongRest.php @@ -0,0 +1,25 @@ +fill([ + 'hp_current' => $sheet->hp_max, + 'hp_temp' => 0, + 'hit_dice_spent' => FifthEdition::hitDiceAfterLongRest($sheet->hit_dice_spent, $sheet->level()), + 'spell_slots' => array_map(fn (array $slot) => ['total' => (int) $slot['total'], 'used' => 0], $sheet->slots()), + ])->save(); + + return $sheet; + } +} diff --git a/app/Actions/Characters/SaveSheet.php b/app/Actions/Characters/SaveSheet.php new file mode 100644 index 0000000..31ce592 --- /dev/null +++ b/app/Actions/Characters/SaveSheet.php @@ -0,0 +1,26 @@ + $parts + */ + public function handle(Entity $character, array $parts): CharacterSheet + { + /** @var CharacterSheet $sheet */ + $sheet = CharacterSheet::query()->updateOrCreate( + ['entity_id' => $character->id], + [...$parts, 'campaign_id' => $character->campaign_id], + ); + + return $sheet; + } +} diff --git a/app/Enums/Ruleset.php b/app/Enums/Ruleset.php index e936aed..5efe08d 100644 --- a/app/Enums/Ruleset.php +++ b/app/Enums/Ruleset.php @@ -32,4 +32,14 @@ public function hasCompendium(): bool { return $this === self::Srd5e2024; } + + /** + * Whether a character on this ruleset gets a sheet of the rules' own shape. The + * card, the write, the export section and the API key all read this rather than + * comparing cases, the compendium's way. + */ + public function hasCharacterSheet(): bool + { + return $this === self::Srd5e2024; + } } diff --git a/app/Http/Controllers/Api/V1/EntityController.php b/app/Http/Controllers/Api/V1/EntityController.php index aba9600..9a2558c 100644 --- a/app/Http/Controllers/Api/V1/EntityController.php +++ b/app/Http/Controllers/Api/V1/EntityController.php @@ -79,6 +79,13 @@ public function show(Campaign $campaign, string $entityId): EntityResource $entity->setRelation('relations', $entity->relations()->visibleTo($user, $role)->with('target')->get()); $entity->setRelation('incomingRelations', $entity->incomingRelations()->visibleTo($user, $role)->with('source')->orderBy('created_at')->get()); + // The ruleset's sheet, only on a ruleset that has one. The relation is set + // either way on a character, so the key is present and null when there is + // no sheet rather than absent, which would read as "hidden". + if ($entity->isCharacter() && $campaign->ruleset->hasCharacterSheet()) { + $entity->setRelation('sheet', $entity->sheet()->first()); + } + if ($entity->isQuest()) { $entity->setRelation('giver', $entity->giver_entity_id === null ? null diff --git a/app/Http/Resources/Api/V1/EntityResource.php b/app/Http/Resources/Api/V1/EntityResource.php index 60a7c76..2f3c5bf 100644 --- a/app/Http/Resources/Api/V1/EntityResource.php +++ b/app/Http/Resources/Api/V1/EntityResource.php @@ -8,6 +8,7 @@ use App\Models\Entity; use App\Models\EntityRelation; use App\Models\QuestObjective; +use App\Support\Sheets\FifthEdition; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; @@ -53,6 +54,53 @@ public function toArray(Request $request): array ]; } + // The ruleset's sheet, on the show route, when the character has one. The + // derived numbers come along because a reader of the API is a reader, and + // the screen prints them too. + $data['sheet'] = $this->whenLoaded('sheet', function () { + $sheet = $this->sheet; + + if ($sheet === null) { + return null; + } + + $sheet->setRelation('character', $this->resource); + + $scores = []; + $modifiers = []; + $saves = []; + $skills = []; + + foreach (array_keys(FifthEdition::ABILITIES) as $ability) { + $scores[$ability] = $sheet->score($ability); + $modifiers[$ability] = $sheet->modifier($ability); + $saves[$ability] = $sheet->saveBonus($ability); + } + + foreach (array_keys(FifthEdition::SKILLS) as $key) { + $skills[$key] = $sheet->skillBonus($key); + } + + return [ + 'scores' => $scores, + 'modifiers' => $modifiers, + 'proficiency_bonus' => $sheet->proficiencyBonus(), + 'saving_throws' => $saves, + 'saving_throw_proficiencies' => $sheet->saving_throws, + 'skills' => $skills, + 'skill_proficiencies' => $sheet->skills, + 'expertise' => $sheet->expertise, + 'passive_perception' => $sheet->passivePerception(), + 'initiative' => $sheet->initiative(), + 'hit_points' => ['max' => $sheet->hp_max, 'current' => $sheet->hp_current, 'temporary' => $sheet->hp_temp], + 'hit_dice' => ['die' => $sheet->hit_die, 'total' => $sheet->level(), 'spent' => $sheet->hit_dice_spent], + 'spell_slots' => (object) array_combine(array_map('strval', array_keys($sheet->slots())), $sheet->slots()), + 'spellcasting_ability' => $sheet->spellcasting_ability, + 'armor_class' => $sheet->armor_class, + 'speed' => $sheet->speed, + ]; + }); + if ($this->isQuest()) { $data['quest'] = [ 'status' => $this->questStatus()?->value, diff --git a/app/Livewire/Characters/Sheet.php b/app/Livewire/Characters/Sheet.php new file mode 100644 index 0000000..1d4cc6e --- /dev/null +++ b/app/Livewire/Characters/Sheet.php @@ -0,0 +1,285 @@ + */ + public array $scores = []; + + /** @var list */ + public array $savingThrows = []; + + /** @var list */ + public array $skills = []; + + /** @var list */ + public array $expertise = []; + + public string $hpMax = ''; + + public string $hpCurrent = ''; + + public string $hpTemp = '0'; + + public string $hitDie = '8'; + + public string $hitDiceSpent = '0'; + + /** @var array */ + public array $spellSlots = []; + + public string $spellcastingAbility = ''; + + public string $armorClass = ''; + + public string $speed = ''; + + public string $damageAmount = ''; + + public string $healAmount = ''; + + public function mount(Campaign $campaign, Entity $character): void + { + $this->enterCampaign($campaign); + + abort_unless($campaign->ruleset->hasCharacterSheet() && $character->isCharacter(), 404); + + $this->authorize('view', $character); + + $this->character = $character; + } + + public function edit(): void + { + $this->authorize('update', $this->character); + + $sheet = $this->sheet(); + + if ($sheet === null) { + $this->scores = array_fill_keys(array_keys(FifthEdition::ABILITIES), 10); + $this->savingThrows = []; + $this->skills = []; + $this->expertise = []; + $this->hpMax = ''; + $this->hpCurrent = ''; + $this->hpTemp = '0'; + $this->hitDie = '8'; + $this->hitDiceSpent = '0'; + $this->spellcastingAbility = ''; + $this->armorClass = ''; + $this->speed = ''; + $slots = []; + } else { + $this->scores = []; + + foreach (array_keys(FifthEdition::ABILITIES) as $ability) { + $this->scores[$ability] = $sheet->score($ability); + } + + $this->savingThrows = $sheet->saving_throws; + $this->skills = $sheet->skills; + $this->expertise = $sheet->expertise; + $this->hpMax = (string) $sheet->hp_max; + $this->hpCurrent = (string) $sheet->hp_current; + $this->hpTemp = (string) $sheet->hp_temp; + $this->hitDie = (string) $sheet->hit_die; + $this->hitDiceSpent = (string) $sheet->hit_dice_spent; + $this->spellcastingAbility = $sheet->spellcasting_ability ?? ''; + $this->armorClass = (string) ($sheet->armor_class ?? ''); + $this->speed = (string) ($sheet->speed ?? ''); + $slots = $sheet->slots(); + } + + // Every level on the form, so a caster can add a slot at a level that had none. + $this->spellSlots = []; + + foreach (range(1, FifthEdition::MAX_SLOT_LEVEL) as $level) { + $this->spellSlots[$level] = $slots[$level] ?? ['total' => 0, 'used' => 0]; + } + + $this->editing = true; + } + + public function cancelEdit(): void + { + $this->editing = false; + } + + public function save(SaveSheet $saveSheet): void + { + $this->authorize('update', $this->character); + + $abilities = array_keys(FifthEdition::ABILITIES); + $skills = array_keys(FifthEdition::SKILLS); + + $validated = $this->validate([ + 'scores' => ['required', 'array:'.implode(',', $abilities)], + 'scores.*' => ['required', 'integer', 'min:'.FifthEdition::MIN_SCORE, 'max:'.FifthEdition::MAX_SCORE], + 'savingThrows' => ['array'], + 'savingThrows.*' => [Rule::in($abilities)], + 'skills' => ['array'], + 'skills.*' => [Rule::in($skills)], + 'expertise' => ['array'], + 'expertise.*' => [Rule::in($skills)], + 'hpMax' => ['required', 'integer', 'min:0', 'max:'.FifthEdition::MAX_HIT_POINTS], + 'hpCurrent' => ['required', 'integer', 'min:0', 'lte:hpMax'], + 'hpTemp' => ['required', 'integer', 'min:0', 'max:'.FifthEdition::MAX_HIT_POINTS], + 'hitDie' => ['required', 'integer', Rule::in(FifthEdition::HIT_DICE)], + 'hitDiceSpent' => ['required', 'integer', 'min:0', 'max:'.FifthEdition::MAX_LEVEL], + 'spellSlots' => ['array'], + 'spellSlots.*.total' => ['required', 'integer', 'min:0', 'max:'.FifthEdition::MAX_SLOTS], + 'spellSlots.*.used' => ['required', 'integer', 'min:0', 'max:'.FifthEdition::MAX_SLOTS], + 'spellcastingAbility' => ['nullable', Rule::in($abilities)], + 'armorClass' => ['nullable', 'integer', 'min:0', 'max:'.FifthEdition::MAX_ARMOR_CLASS], + 'speed' => ['nullable', 'integer', 'min:0', 'max:'.FifthEdition::MAX_SPEED], + ], [ + 'hpCurrent.lte' => 'Current hit points cannot be above the maximum.', + 'skills.*.in' => 'That is not a skill the rules name.', + ]); + + $slots = []; + + foreach ($validated['spellSlots'] ?? [] as $level => $slot) { + $total = (int) $slot['total']; + + if ($total > 0) { + $slots[(int) $level] = ['total' => $total, 'used' => min($total, (int) $slot['used'])]; + } + } + + $parts = [ + 'saving_throws' => array_values(array_unique($validated['savingThrows'] ?? [])), + 'skills' => array_values(array_unique($validated['skills'] ?? [])), + 'expertise' => array_values(array_unique($validated['expertise'] ?? [])), + 'hp_max' => (int) $validated['hpMax'], + 'hp_current' => (int) $validated['hpCurrent'], + 'hp_temp' => (int) $validated['hpTemp'], + 'hit_die' => (int) $validated['hitDie'], + 'hit_dice_spent' => (int) $validated['hitDiceSpent'], + 'spell_slots' => $slots, + 'spellcasting_ability' => filled($validated['spellcastingAbility'] ?? null) ? $validated['spellcastingAbility'] : null, + 'armor_class' => filled($validated['armorClass'] ?? null) ? (int) $validated['armorClass'] : null, + 'speed' => filled($validated['speed'] ?? null) ? (int) $validated['speed'] : null, + ]; + + foreach (CharacterSheet::SCORE_COLUMNS as $ability => $column) { + $parts[$column] = (int) $validated['scores'][$ability]; + } + + $saveSheet->handle($this->character, $parts); + + $this->editing = false; + } + + public function damage(AdjustHitPoints $adjust): void + { + $this->authorize('update', $this->character); + + $sheet = $this->sheet(); + + abort_if($sheet === null, 404); + + $validated = $this->validate(['damageAmount' => ['required', 'integer', 'min:1', 'max:'.FifthEdition::MAX_HIT_POINTS]]); + + $adjust->damage($sheet, (int) $validated['damageAmount']); + + $this->reset('damageAmount'); + } + + public function heal(AdjustHitPoints $adjust): void + { + $this->authorize('update', $this->character); + + $sheet = $this->sheet(); + + abort_if($sheet === null, 404); + + $validated = $this->validate(['healAmount' => ['required', 'integer', 'min:1', 'max:'.FifthEdition::MAX_HIT_POINTS]]); + + $adjust->heal($sheet, (int) $validated['healAmount']); + + $this->reset('healAmount'); + } + + public function longRest(LongRest $longRest): void + { + $this->authorize('update', $this->character); + + $sheet = $this->sheet(); + + abort_if($sheet === null, 404); + + $longRest->handle($sheet); + } + + public function render(): View + { + $sheet = $this->sheet(); + + return view('livewire.characters.sheet', [ + 'sheet' => $sheet, + 'canWrite' => $this->user()->can('update', $this->character), + 'abilities' => FifthEdition::ABILITIES, + 'skillList' => FifthEdition::SKILLS, + 'hitDice' => FifthEdition::HIT_DICE, + 'slotLevels' => range(1, FifthEdition::MAX_SLOT_LEVEL), + 'attribution' => config('compendium.attribution'), + // The party's pack, as the ledger page shows it. There is no second purse. + 'pack' => LedgerEntry::inventory(LedgerEntry::query()->items()->orderBy('created_at')->get()), + ]); + } + + private function sheet(): ?CharacterSheet + { + $sheet = CharacterSheet::query()->where('entity_id', $this->character->id)->first(); + + $sheet?->setRelation('character', $this->character); + + return $sheet; + } + + private function user(): User + { + /** @var User $user */ + $user = auth()->user(); + + return $user; + } +} diff --git a/app/Livewire/Entities/Show.php b/app/Livewire/Entities/Show.php index dcd170a..6e13f46 100644 --- a/app/Livewire/Entities/Show.php +++ b/app/Livewire/Entities/Show.php @@ -119,6 +119,9 @@ public function render(MarkdownRenderer $renderer): View 'dmNotesHtml' => $role->isDm() ? $renderer->render($this->entity->dm_notes, $wikiLinks) : null, 'rewardsHtml' => $this->entity->isQuest() ? $renderer->render($this->entity->rewards, $wikiLinks) : '', 'questStatus' => $this->entity->questStatus(), + // The SRD 5.2.1 sheet is a ruleset module: the card mounts only on a campaign + // whose ruleset has one, and a page on any other ruleset never asks for it. + 'showSheet' => $this->entity->isCharacter() && $this->campaign->ruleset->hasCharacterSheet(), // A PC always carries the downtime card, so its player has the form. An NPC // carries it once a GM has written a row, and never an empty one. 'showDowntime' => $this->entity->isCharacter() diff --git a/app/Models/CharacterSheet.php b/app/Models/CharacterSheet.php new file mode 100644 index 0000000..ec5c99e --- /dev/null +++ b/app/Models/CharacterSheet.php @@ -0,0 +1,221 @@ + $saving_throws + * @property list $skills + * @property list $expertise + * @property int $hp_max + * @property int $hp_current + * @property int $hp_temp + * @property int $hit_die + * @property int $hit_dice_spent + * @property array $spell_slots JSON hands the levels back as strings. + * @property string|null $spellcasting_ability + * @property int|null $armor_class + * @property int|null $speed + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property-read Campaign $campaign + * @property-read Entity $character + */ +#[Fillable([ + 'campaign_id', 'entity_id', 'strength', 'dexterity', 'constitution', 'intelligence', 'wisdom', 'charisma', + 'saving_throws', 'skills', 'expertise', 'hp_max', 'hp_current', 'hp_temp', 'hit_die', 'hit_dice_spent', + 'spell_slots', 'spellcasting_ability', 'armor_class', 'speed', +])] +class CharacterSheet extends Model +{ + use BelongsToCampaign; + + /** @use HasFactory */ + use HasFactory, HasUlids; + + /** @var array Ability key to the column that holds its score. */ + public const SCORE_COLUMNS = [ + 'str' => 'strength', + 'dex' => 'dexterity', + 'con' => 'constitution', + 'int' => 'intelligence', + 'wis' => 'wisdom', + 'cha' => 'charisma', + ]; + + /** + * The column defaults, for an instance that has not been read back from the row. + * + * @var array + */ + protected $attributes = [ + 'saving_throws' => '[]', + 'skills' => '[]', + 'expertise' => '[]', + 'spell_slots' => '[]', + ]; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'strength' => 'integer', + 'dexterity' => 'integer', + 'constitution' => 'integer', + 'intelligence' => 'integer', + 'wisdom' => 'integer', + 'charisma' => 'integer', + 'saving_throws' => 'array', + 'skills' => 'array', + 'expertise' => 'array', + 'hp_max' => 'integer', + 'hp_current' => 'integer', + 'hp_temp' => 'integer', + 'hit_die' => 'integer', + 'hit_dice_spent' => 'integer', + 'spell_slots' => 'array', + 'armor_class' => 'integer', + 'speed' => 'integer', + ]; + } + + /** + * @return BelongsTo + */ + public function character(): BelongsTo + { + return $this->belongsTo(Entity::class, 'entity_id'); + } + + /** + * The character's own level. A character with none yet computes at level one. + */ + public function level(): int + { + return max(1, $this->character->level ?? 1); + } + + public function score(string $ability): int + { + return (int) $this->{self::SCORE_COLUMNS[$ability]}; + } + + public function modifier(string $ability): int + { + return FifthEdition::modifier($this->score($ability)); + } + + public function proficiencyBonus(): int + { + return FifthEdition::proficiencyBonus($this->level()); + } + + public function hasSaveProficiency(string $ability): bool + { + return in_array($ability, $this->saving_throws, true); + } + + public function saveBonus(string $ability): int + { + return FifthEdition::saveBonus($this->score($ability), $this->hasSaveProficiency($ability), $this->level()); + } + + public function hasSkillProficiency(string $skill): bool + { + return in_array($skill, $this->skills, true); + } + + public function hasExpertise(string $skill): bool + { + return in_array($skill, $this->expertise, true); + } + + public function skillBonus(string $skill): int + { + return FifthEdition::skillBonus( + $this->score(FifthEdition::SKILLS[$skill]['ability']), + $this->hasSkillProficiency($skill), + $this->hasExpertise($skill), + $this->level(), + ); + } + + public function passivePerception(): int + { + return 10 + $this->skillBonus('perception'); + } + + public function initiative(): int + { + return $this->modifier('dex'); + } + + /** + * "5d8": the level's worth of the one die size, less what is spent when asked. + */ + public function hitDiceLeft(): int + { + return max(0, $this->level() - $this->hit_dice_spent); + } + + public function hitDiceLabel(): string + { + return $this->level().'d'.$this->hit_die; + } + + /** + * The slots, level by level, only the levels with a slot. Keys are ints whatever + * JSON handed back. + * + * @return array + */ + public function slots(): array + { + $slots = []; + + foreach ($this->spell_slots as $level => $slot) { + $total = $slot['total']; + + if ($total > 0) { + $slots[(int) $level] = ['total' => $total, 'used' => min($total, $slot['used'])]; + } + } + + ksort($slots); + + return $slots; + } + + public function hasSlots(): bool + { + return $this->slots() !== []; + } +} diff --git a/app/Models/Entity.php b/app/Models/Entity.php index 917aa00..e18ba4a 100644 --- a/app/Models/Entity.php +++ b/app/Models/Entity.php @@ -21,6 +21,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\Pivot; use Illuminate\Database\Eloquent\SoftDeletes; @@ -373,6 +374,16 @@ public function downtimeActivities(): HasMany return $this->hasMany(DowntimeActivity::class, 'entity_id')->orderBy('created_at')->orderBy('id'); } + /** + * The SRD 5.2.1 sheet, on a campaign whose ruleset has one. Null otherwise. + * + * @return HasOne + */ + public function sheet(): HasOne + { + return $this->hasOne(CharacterSheet::class, 'entity_id'); + } + public function isCharacter(): bool { return $this->type === EntityType::Character; diff --git a/app/Support/Sheets/FifthEdition.php b/app/Support/Sheets/FifthEdition.php new file mode 100644 index 0000000..a1bc2bd --- /dev/null +++ b/app/Support/Sheets/FifthEdition.php @@ -0,0 +1,114 @@ + */ + public const HIT_DICE = [6, 8, 10, 12]; + + /** @var array */ + public const ABILITIES = [ + 'str' => 'Strength', + 'dex' => 'Dexterity', + 'con' => 'Constitution', + 'int' => 'Intelligence', + 'wis' => 'Wisdom', + 'cha' => 'Charisma', + ]; + + /** @var array */ + public const SKILLS = [ + 'acrobatics' => ['name' => 'Acrobatics', 'ability' => 'dex'], + 'animal_handling' => ['name' => 'Animal Handling', 'ability' => 'wis'], + 'arcana' => ['name' => 'Arcana', 'ability' => 'int'], + 'athletics' => ['name' => 'Athletics', 'ability' => 'str'], + 'deception' => ['name' => 'Deception', 'ability' => 'cha'], + 'history' => ['name' => 'History', 'ability' => 'int'], + 'insight' => ['name' => 'Insight', 'ability' => 'wis'], + 'intimidation' => ['name' => 'Intimidation', 'ability' => 'cha'], + 'investigation' => ['name' => 'Investigation', 'ability' => 'int'], + 'medicine' => ['name' => 'Medicine', 'ability' => 'wis'], + 'nature' => ['name' => 'Nature', 'ability' => 'int'], + 'perception' => ['name' => 'Perception', 'ability' => 'wis'], + 'performance' => ['name' => 'Performance', 'ability' => 'cha'], + 'persuasion' => ['name' => 'Persuasion', 'ability' => 'cha'], + 'religion' => ['name' => 'Religion', 'ability' => 'int'], + 'sleight_of_hand' => ['name' => 'Sleight of Hand', 'ability' => 'dex'], + 'stealth' => ['name' => 'Stealth', 'ability' => 'dex'], + 'survival' => ['name' => 'Survival', 'ability' => 'wis'], + ]; + + public static function modifier(int $score): int + { + return (int) floor(($score - 10) / 2); + } + + /** + * Two at level one, and one more every four levels. A character with no level + * yet computes at level one. + */ + public static function proficiencyBonus(int $level): int + { + return 2 + intdiv(max(1, $level) - 1, 4); + } + + public static function saveBonus(int $score, bool $proficient, int $level): int + { + return self::modifier($score) + ($proficient ? self::proficiencyBonus($level) : 0); + } + + /** + * Expertise doubles the proficiency bonus. Expertise without proficiency is a + * form mistake, and it reads as proficiency rather than as nothing. + */ + public static function skillBonus(int $score, bool $proficient, bool $expertise, int $level): int + { + $bonus = self::proficiencyBonus($level); + + return self::modifier($score) + match (true) { + $proficient && $expertise => 2 * $bonus, + $proficient || $expertise => $bonus, + default => 0, + }; + } + + /** + * A long rest gives back half the hit dice, rounded down, and at least one. + */ + public static function hitDiceAfterLongRest(int $spent, int $level): int + { + return max(0, $spent - max(1, intdiv(max(1, $level), 2))); + } + + public static function signed(int $bonus): string + { + return ($bonus < 0 ? '' : '+').$bonus; + } +} diff --git a/database/factories/CharacterSheetFactory.php b/database/factories/CharacterSheetFactory.php new file mode 100644 index 0000000..95126ea --- /dev/null +++ b/database/factories/CharacterSheetFactory.php @@ -0,0 +1,51 @@ + + */ +class CharacterSheetFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'campaign_id' => Campaign::factory(), + 'entity_id' => Entity::factory(), + 'strength' => 10, + 'dexterity' => 10, + 'constitution' => 10, + 'intelligence' => 10, + 'wisdom' => 10, + 'charisma' => 10, + 'saving_throws' => [], + 'skills' => [], + 'expertise' => [], + 'hp_max' => 10, + 'hp_current' => 10, + 'hp_temp' => 0, + 'hit_die' => 8, + 'hit_dice_spent' => 0, + 'spell_slots' => [], + 'spellcasting_ability' => null, + 'armor_class' => null, + 'speed' => null, + ]; + } + + public function forCharacter(Entity $character): static + { + return $this->state([ + 'campaign_id' => $character->campaign_id, + 'entity_id' => $character->id, + ]); + } +} diff --git a/database/migrations/2026_09_13_195056_create_character_sheets_table.php b/database/migrations/2026_09_13_195056_create_character_sheets_table.php new file mode 100644 index 0000000..a56dd29 --- /dev/null +++ b/database/migrations/2026_09_13_195056_create_character_sheets_table.php @@ -0,0 +1,55 @@ +ulid('id')->primary(); + $table->foreignUlid('campaign_id')->constrained()->cascadeOnDelete(); + $table->foreignUlid('entity_id')->unique()->constrained('entities')->cascadeOnDelete(); + $table->unsignedSmallInteger('strength')->default(10); + $table->unsignedSmallInteger('dexterity')->default(10); + $table->unsignedSmallInteger('constitution')->default(10); + $table->unsignedSmallInteger('intelligence')->default(10); + $table->unsignedSmallInteger('wisdom')->default(10); + $table->unsignedSmallInteger('charisma')->default(10); + $table->text('saving_throws'); + $table->text('skills'); + $table->text('expertise'); + $table->unsignedSmallInteger('hp_max')->default(0); + $table->unsignedSmallInteger('hp_current')->default(0); + $table->unsignedSmallInteger('hp_temp')->default(0); + $table->unsignedSmallInteger('hit_die')->default(8); + $table->unsignedSmallInteger('hit_dice_spent')->default(0); + $table->text('spell_slots'); + $table->string('spellcasting_ability', 3)->nullable(); + $table->unsignedSmallInteger('armor_class')->nullable(); + $table->unsignedSmallInteger('speed')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('character_sheets'); + } +}; diff --git a/database/seeders/DemoCampaignSeeder.php b/database/seeders/DemoCampaignSeeder.php index bf15cf5..732164f 100644 --- a/database/seeders/DemoCampaignSeeder.php +++ b/database/seeders/DemoCampaignSeeder.php @@ -4,6 +4,7 @@ use App\Actions\Calendars\SaveCalendar; use App\Actions\Campaigns\CreateCampaign; +use App\Actions\Characters\SaveSheet; use App\Actions\Clocks\CreateClock; use App\Actions\Clocks\SetClockVisibility; use App\Actions\Clocks\TickClock; @@ -209,6 +210,7 @@ public function run(): void $this->seedReputation($campaign, $dm); $this->seedLedger($campaign, $dm, $player); $this->seedDowntime($campaign, $dm, $player); + $this->seedSheets($campaign); $this->seedEncounter($campaign, $dm); $this->seedTables($campaign, $dm); $this->seedGenerators($campaign, $dm); @@ -519,6 +521,41 @@ private function seedLedger(Campaign $campaign, User $dm, User $player): void $record->item($campaign, $player, 'Torch', -2, null, 'Burned in the corridor', $second); } + /** + * The two PCs' sheets, on the rules the campaign runs: a rogue with expertise in + * Stealth and a cleric with slots half spent, so the page has numbers on it and + * the long rest has something to give back. + */ + private function seedSheets(Campaign $campaign): void + { + $save = app(SaveSheet::class); + $named = fn (string $name): Entity => $campaign->entities()->where('name', $name)->firstOrFail(); + + $save->handle($named('Wren Ashgrove'), [ + 'strength' => 10, 'dexterity' => 17, 'constitution' => 14, 'intelligence' => 12, 'wisdom' => 14, 'charisma' => 8, + 'saving_throws' => ['dex', 'int'], + 'skills' => ['stealth', 'sleight_of_hand', 'perception', 'acrobatics', 'deception'], + 'expertise' => ['stealth', 'sleight_of_hand'], + 'hp_max' => 38, 'hp_current' => 31, 'hp_temp' => 0, + 'hit_die' => 8, 'hit_dice_spent' => 1, + 'spell_slots' => [], + 'spellcasting_ability' => null, + 'armor_class' => 15, 'speed' => 30, + ]); + + $save->handle($named('Halder Bream'), [ + 'strength' => 14, 'dexterity' => 10, 'constitution' => 15, 'intelligence' => 11, 'wisdom' => 17, 'charisma' => 13, + 'saving_throws' => ['wis', 'cha'], + 'skills' => ['insight', 'medicine', 'religion'], + 'expertise' => [], + 'hp_max' => 43, 'hp_current' => 43, 'hp_temp' => 0, + 'hit_die' => 8, 'hit_dice_spent' => 0, + 'spell_slots' => [1 => ['total' => 4, 'used' => 2], 2 => ['total' => 3, 'used' => 1], 3 => ['total' => 2, 'used' => 0]], + 'spellcasting_ability' => 'wis', + 'armor_class' => 18, 'speed' => 30, + ]); + } + /** * What the party did in the fortnight between the first two sessions: two rows * of Wren's, written by her player, and one of Halder's, written by the GM, each diff --git a/docs/plans/2026-09-13-feat-character-sheet-plan.md b/docs/plans/2026-09-13-feat-character-sheet-plan.md new file mode 100644 index 0000000..80b6e5e --- /dev/null +++ b/docs/plans/2026-09-13-feat-character-sheet-plan.md @@ -0,0 +1,182 @@ +--- +title: "feat: The 5e character sheet, as a ruleset module" +type: feat +date: 2026-09-13 +status: implemented +brainstorm: docs/brainstorms/2026-09-02-demgem-campaign-manager-brainstorm.md +follows: docs/plans/2026-09-13-feat-family-trees-plan.md +--- + +# feat: The 5e character sheet, as a ruleset module + +## Overview + +The brainstorm's players table lists "Full 5e character sheet" under P3 with one note: "Ruleset module." The core of demgem is system-agnostic: a character has a class, a level, and a link to the sheet a player actually plays from. Slices 15 to 17 built the seam a ruleset adds its module through, `Ruleset::hasCompendium()` and `config/encounters.php`. This slice adds the second module through the same seam: a sheet with the numbers a table on the SRD 5.2.1 rules reads out loud. + +| Feature | What it adds | +|---|---| +| The sheet | Six ability scores, saving throw and skill proficiencies, hit points and hit dice, spell slots, armour class and speed. One row per character, in its own table. | +| The maths | Modifiers, the proficiency bonus from the level, every save and skill bonus, passive perception, and the initiative bonus, computed on every read from the stored scores. Nothing derived is stored. | +| The seam | `Ruleset::hasCharacterSheet()`. The card, the write, the export section, and the API key all read it, so a campaign on the system-agnostic ruleset never sees the sheet. | +| Who writes it | The character's player, or a GM: `EntityPolicy::update()`'s rule, the same one the class and level already use. | +| The inventory | The party's pack, read from the ledger on the sheet. No second purse. | +| The round trip | The sheet travels nested under its character in the export, the reader, the importer, and the vault. | + +When this slice is done Wren's player opens her page in The Drowned Duchy and reads a sheet: Dexterity 17, +3, Stealth +6 with expertise, 38 of 38 hit points, five d8 hit dice, and the party's pack under it. They take 12 damage, press "Long rest" at the end of the night, and the sheet is whole again. Halder's cleric sheet shows four first-level slots and two second, two of them spent. + +**On scope.** Phase 0 is the seam, the table, the maths, and the policy. Phase 1 is the card: reading and editing. Phase 2 is the export, the API, the seeder, the rules, and the pass. + +## Problem Statement + +**A link to a sheet somewhere else is not a sheet.** `sheet_url` was the right call for a system-agnostic core: a table on any system has some site it plays from. A table on the SRD 5.2.1 rules is the one this app already carries a compendium and a fight budget for, and its players still tab out to read their own Stealth bonus. + +**The numbers the table reads out loud are derived, and every sheet site stores them.** A modifier is the score; a save is the modifier and maybe the proficiency bonus; the bonus is the level. Storing any of those is the second source of truth that drifts, the ledger's rule. The sheet stores what a player decides and computes what the rules decide. + +**A module must not leak into the core.** Six ability scores as columns on `entities` would put one ruleset's shape on every campaign's table, and the next ruleset would add six more. The compendium answered this with a seam and a config; the sheet is one table behind the same seam. + +## Proposed Solution + +**One table, one row per character, behind the seam.** `character_sheets` holds what a player decides: the six scores, which saves and skills carry proficiency and which skills expertise, the hit point maximum, current and temporary, the hit die size and how many are spent, the spell slots per level with how many are used, the spellcasting ability, the armour class, and the speed. The proficiency lists and the slots are JSON on the row, the calendar's recorded exception: one configuration read whole, replaced whole on save, never queried by row, never gated. + +**The maths is a pure class.** `Support\Sheets\FifthEdition` knows the six abilities, the eighteen skills and which ability each uses, the modifier of a score, the proficiency bonus at a level, and the bonus of a save or a skill given the sheet. It is unit-tested and has no model in it. The level is the character's own `level`, so the sheet does not carry one. + +**The card reads for whoever may read the character and writes for whoever may edit it.** `Characters\Sheet` is nested on the character's page when the campaign's ruleset has a sheet. A player reads the party's sheets and edits their own; a GM edits any. Editing is a form on the card, every field at once, validated against the bounds. Three quick presses beside it, because a table does these every hour: damage, healing, and a long rest. + +**The inventory is the ledger.** The sheet's last section is the party's pack through `LedgerEntry::inventory()`, exactly as the ledger page shows it. The ledger is the party's, so the section says so. + +## Technical Approach + +### No new dependency + +### What slices 1 to 26 give us for free + +| Piece | Reuse | +|---|---| +| `Ruleset::hasCompendium()` | The seam's shape. `hasCharacterSheet()` sits beside it. | +| `EntityPolicy::update()` | Who writes a character's things. | +| `Entity::level`, `character_class` | The level the proficiency bonus comes from. | +| `LedgerEntry::inventory()` | The pack. | +| `StatBlock::ability_scores` | The six abbreviations and the score/modifier shape the compendium already prints. | +| `config('compendium.attribution')` | The ability and skill names are SRD terms, and the card carries the notice the compendium carries. | +| `ExportCampaign::NESTED_TABLES` | One-to-one with a character, so nested under it. | + +### The data + +``` +character_sheets + id ulid + campaign_id ulid -> campaigns, cascade + entity_id ulid -> entities, cascade, unique + strength, dexterity, constitution, intelligence, wisdom, charisma smallint, 1..30, default 10 + saving_throws json list of ability keys with proficiency + skills json list of skill keys with proficiency + expertise json list of skill keys with expertise + hp_max smallint unsigned, 0..999 + hp_current smallint unsigned, 0..999 + hp_temp smallint unsigned, 0..999 + hit_die smallint, one of 6, 8, 10, 12 + hit_dice_spent smallint unsigned, 0..level + spell_slots json map, level 1..9 => {total, used} + spellcasting_ability string(3) nullable, an ability key + armor_class smallint nullable + speed smallint nullable + created_at, updated_at +``` + +Nothing derived is stored: no modifier, no proficiency bonus, no passive perception, no initiative bonus. + +### Scope and decisions + +| Question | Decision | +|---|---| +| Which rulesets | `Ruleset::hasCharacterSheet()`, true for SRD 5.2.1 alone. The card, the write, the export, and the API all read it. | +| Which characters | Any character on that ruleset. A GM may keep a sheet for an NPC. | +| Who reads | Whoever may read the character. The sheet has no gate of its own. | +| Who writes | A GM, or the character's player. Not the party. | +| The level | The character's own. A sheet with no level on its character computes at level 1. | +| Hit dice | One die size, `hit_die`, and the count is the level. Multiclassing is a follow-up. | +| Spell slots | Nine levels, total and used each, edited by hand. No spell list: a list of spells is a different slice. | +| Long rest | Hit points to the maximum, temporary hit points to zero, every slot's used to zero, hit dice spent reduced by half the level rounded down, the rule as the SRD states it. | +| Damage and healing | Damage comes off temporary hit points first, then current, never below zero. Healing adds to current, never above the maximum. | +| The attribution | The card prints the compendium's notice, because the ability and skill names are SRD terms. | +| The export | Nested under the character as `sheet`, null when there is none. The reader refuses a score outside the bounds rather than clamping it. | +| The API | `sheet` on the show route for a character that has one, on a ruleset with sheets. No API write this slice. | +| The vault | A "Character sheet" section on the character's page: the scores with modifiers, hit points, hit dice, and slots. | + +### Actions + +| Action | Does | +|---|---| +| `Characters\SaveSheet` | Creates or replaces the sheet from validated parts. | +| `Characters\AdjustHitPoints` | Damage or healing, by the two rules above. | +| `Characters\LongRest` | The long rest. | + +### Screens + +- **The character's page** gains a "Character sheet" card under the record row: abilities in a six-column grid with score and modifier, saves and skills in two columns with the proficiency mark and the bonus, hit points with the three numbers and the two quick inputs, hit dice, spell slots as pips, armour class, speed, initiative, passive perception, the party's pack, and for a writer the "Edit sheet" form and "Long rest". + +### The round trip + +- `character_sheets` joins `NESTED_TABLES` as `entities[].sheet`. The reader validates every number against the bounds. The importer writes it after the entity. +- No version bump. + +## Verification + + php artisan test --compact tests/Unit/Sheets + php artisan test --compact tests/Feature/Characters + php artisan test --compact tests/Feature/Api + php artisan test --compact --filter=RoundTrip + php artisan test --compact --filter=DemoSeeder + vendor/bin/pint --dirty --format agent + vendor/bin/phpstan analyse + +Then the full suite with `memory_limit=1G`, and a browser pass: as the player, open Wren, read the sheet, take damage, press "Long rest"; as the GM, edit Halder's slots; switch the campaign to the system-agnostic ruleset and find no card. + +## Open Questions + +1. **Should the sheet carry a spell list?** Recommendation: not now. The SRD's spells are a dataset the way its creatures are, and that is a compendium slice. +2. **Should the level move onto the sheet?** Recommendation: no. The level is a core fact every ruleset has. +3. **Should the API write the sheet?** Recommendation: a follow-up, once the form has been used for a while. + +## References + +- `.ai/rules/commands.md` — the licence follows the words; the notice renders wherever SRD terms appear. +- `.ai/rules/models.md` — a scalar gets a column, a list gets a child table, and the calendar's JSON exception. +- `.ai/rules/entities.md` — the character fields are not DM fields; the owning player edits their own PC. +- `.ai/rules/campaigns.md` — a new campaign-scoped table joins the export in the same commit. + +## Implementation Results — 2026-09-13 + +Implemented in full. 34 new tests, 24 of them unit tests on the maths; the suite is 1476 tests, 1475 passing, 1 skipped, with Larastan clean and Pint clean. + +### What shipped, against the plan + +| Planned | Shipped | +|---|---| +| The seam | `Ruleset::hasCharacterSheet()`. The component aborts 404 without it, the page does not mount the card, and the API sets the relation only on such a campaign. | +| `character_sheets` | As planned. The three lists and the slots are JSON on the row. Nothing derived is stored. | +| The maths | `Support\Sheets\FifthEdition`, pure and unit-tested; `CharacterSheet` wraps it with the character's level. | +| The card | Reading, one form for every field, damage, healing, and the long rest, with the compendium's attribution under it and the party's pack from the ledger. | +| Who writes | `EntityPolicy::update()`, with no policy of the sheet's own. | +| The round trip and the vault | Nested under the character as `sheet`; the reader refuses a score outside the bounds and clamps the rest; the vault page gains a "Character sheet" section with the derived numbers printed. | +| The API | `sheet` on the show route, with the derived numbers beside the stored ones. | +| The demo world | Wren's rogue and Halder's cleric, the cleric with slots half spent. | + +### Deviations + +| Planned | Shipped | Why | +|---|---|---| +| A browser check that switches the campaign to the system-agnostic ruleset | A test instead | The ruleset is chosen at creation and settings do not change it, so the check is `offers no sheet on a system-agnostic campaign` in the feature test. | +| The spell save DC and attack bonus were not in the plan | Printed on the slots block when a spellcasting ability is set | Two numbers the same maths gives for free, and the table reads them as often as the slots. | + +### Browser checks + +Driven end to end on the seeded world at 1100px as the player and 1400px as the GM: + +- Wren's page shows the player "No sheet yet" and "Edit sheet". The form takes the six scores, two saving throws, Stealth with expertise, Perception, 38 hit points with 5 temporary, a d8, armour class 15 and speed 30, and the card reads Dexterity 17 +3, Stealth +9, Perception +5, save +6 on Dexterity, Passive Perception 15, initiative +3, and "5 of 5d8". +- Taking 12 damage reads "31 / 38" with the temporary hit points gone. "Long rest" reads "38 / 38". +- The GM opens the same page and reads the sheet with "Edit sheet" and "Long rest", and the attribution notice under it. + +### A flake found on the way + +The first CI run failed `BuildArchiveTest` on PostgreSQL: the entities export ordered by `created_at` alone, PostgreSQL keeps timestamps to the second, and two pages made in one second came out in either order, which moved a media ordinal. The export now breaks the tie on the id, as the other sections do. It is not this slice's, and it is fixed here because it was found here. diff --git a/resources/views/livewire/characters/sheet.blade.php b/resources/views/livewire/characters/sheet.blade.php new file mode 100644 index 0000000..7f2bf3f --- /dev/null +++ b/resources/views/livewire/characters/sheet.blade.php @@ -0,0 +1,202 @@ +{{-- + The SRD 5.2.1 sheet. Every number on it that is not a score was computed in the + model on this render; nothing here does arithmetic. The form appears for whoever + may edit the character, and the policy decided that, not this file. +--}} +
+ @if ($editing) +
+
+

Ability scores

+
+ @foreach ($abilities as $ability => $name) + + @endforeach +
+
+ +
+
+

Saving throws

+
+ @foreach ($abilities as $ability => $name) + + @endforeach +
+
+
+

Hit points

+
+ + + +
+
+ + @foreach ($hitDice as $die) + + @endforeach + + + +
+
+ + + + @foreach ($abilities as $ability => $name) + + @endforeach + +
+
+
+ +
+

Skills

+

Tick a skill for proficiency, and the second box for expertise.

+
+ @foreach ($skillList as $key => $skill) +
+ + +
+ @endforeach +
+
+ +
+

Spell slots

+
+ @foreach ($slotLevels as $level) +
+

Level {{ $level }}

+ + +
+ @endforeach +
+
+ +
+ Save sheet + Cancel +
+
+ @elseif ($sheet === null) +
+

No sheet yet. {{ $canWrite ? 'Write the scores and the rest follows.' : 'The player has not written one.' }}

+ @if ($canWrite) + Edit sheet + @endif +
+ @else +
+ Proficiency bonus {{ \App\Support\Sheets\FifthEdition::signed($sheet->proficiencyBonus()) }} + Initiative {{ \App\Support\Sheets\FifthEdition::signed($sheet->initiative()) }} + @if ($sheet->armor_class !== null) + Armour class {{ $sheet->armor_class }} + @endif + @if ($sheet->speed !== null) + Speed {{ $sheet->speed }} + @endif + Passive Perception {{ $sheet->passivePerception() }} + @if ($canWrite) + + Edit sheet + Long rest + + @endif +
+ +
+ @foreach ($abilities as $ability => $name) +
+

{{ $name }}

+

{{ $sheet->score($ability) }}

+

{{ \App\Support\Sheets\FifthEdition::signed($sheet->modifier($ability)) }}

+

Save {{ \App\Support\Sheets\FifthEdition::signed($sheet->saveBonus($ability)) }}

+
+ @endforeach +
+ +
+
    + @foreach ($skillList as $key => $skill) +
  • + + {{ $skill['name'] }} ({{ strtoupper($skill['ability']) }}) + {{ \App\Support\Sheets\FifthEdition::signed($sheet->skillBonus($key)) }} +
  • + @endforeach +
+ +
+
+

Hit points

+

+ {{ $sheet->hp_current }} / {{ $sheet->hp_max }} +

+ @if ($sheet->hp_temp > 0) +

+{{ $sheet->hp_temp }} temporary

+ @endif +

Hit dice {{ $sheet->hitDiceLeft() }} of {{ $sheet->hitDiceLabel() }}

+ + @if ($canWrite) +
+
+
+ +
+ Take +
+
+
+ +
+ Heal +
+
+ @endif +
+ + @if ($sheet->hasSlots()) +
+

Spell slots

+ @if ($sheet->spellcasting_ability) +

{{ $abilities[$sheet->spellcasting_ability] }} · save DC {{ 8 + $sheet->proficiencyBonus() + $sheet->modifier($sheet->spellcasting_ability) }} · attack {{ \App\Support\Sheets\FifthEdition::signed($sheet->proficiencyBonus() + $sheet->modifier($sheet->spellcasting_ability)) }}

+ @endif +
    + @foreach ($sheet->slots() as $level => $slot) +
  • + L{{ $level }} + + @foreach (range(1, $slot['total']) as $pip) + + @endforeach + +
  • + @endforeach +
+
+ @endif +
+
+ @endif + +
+

The party's pack

+ @if ($pack === []) +

Nothing in the pack. The ledger is where it goes in.

+ @else +
    + @foreach ($pack as $line) +
  • {{ $line['quantity'] }} × {{ $line['name'] }}
  • + @endforeach +
+ @endif +

The ledger is the party's; every member writes to it.

+
+ +

{{ $attribution }}

+
diff --git a/resources/views/livewire/entities/show.blade.php b/resources/views/livewire/entities/show.blade.php index 5c7dc82..db740c8 100644 --- a/resources/views/livewire/entities/show.blade.php +++ b/resources/views/livewire/entities/show.blade.php @@ -165,6 +165,13 @@ class="ml-auto" @endif + {{-- The ruleset's own sheet, on a campaign whose ruleset has one. --}} + @if ($showSheet) + + + + @endif + @if ($entity->isArc()) @if ($arcQuests->isEmpty()) diff --git a/tests/Feature/Campaigns/DemoSeederTest.php b/tests/Feature/Campaigns/DemoSeederTest.php index 732b801..2435345 100644 --- a/tests/Feature/Campaigns/DemoSeederTest.php +++ b/tests/Feature/Campaigns/DemoSeederTest.php @@ -2,6 +2,7 @@ use App\Enums\CampaignRole; use App\Models\Campaign; +use App\Models\CharacterSheet; use App\Models\Decision; use App\Models\DowntimeActivity; use App\Models\Encounter; @@ -35,6 +36,7 @@ ->and($campaign->roleFor($player))->toBe(CampaignRole::Player) ->and($campaign->screen()->entity?->name)->toBe("The duke's letter") ->and((int) DowntimeActivity::query()->sum('days'))->toBe(15) + ->and(CharacterSheet::query()->count())->toBe(2) ->and(Entity::query()->count())->toBeGreaterThan(10) ->and(EntityTemplate::query()->count())->toBe(2) ->and(GameSession::query()->count())->toBe(4) diff --git a/tests/Feature/Characters/CharacterSheetTest.php b/tests/Feature/Characters/CharacterSheetTest.php new file mode 100644 index 0000000..fc5a28e --- /dev/null +++ b/tests/Feature/Characters/CharacterSheetTest.php @@ -0,0 +1,314 @@ +create(['ruleset' => Ruleset::Srd5e2024]); + $tobin = memberOf($campaign, CampaignRole::Player); + $mira = memberOf($campaign, CampaignRole::Player); + + $wren = Entity::factory()->for($campaign)->pcOf($tobin)->forPlayers()->withRecord('Rogue', 5, null) + ->create(['name' => 'Wren Ashgrove', 'slug' => 'wren-ashgrove']); + $halder = Entity::factory()->for($campaign)->pcOf($mira)->forPlayers()->withRecord('Cleric', 5, null) + ->create(['name' => 'Halder Bream', 'slug' => 'halder-bream']); + $abbess = Entity::factory()->for($campaign)->type(EntityType::Character)->forPlayers() + ->create(['name' => 'Abbess Corvane', 'slug' => 'abbess-corvane']); + + return compact('campaign', 'tobin', 'mira', 'wren', 'halder', 'abbess'); +} + +function sheetOf(Entity $character, User $viewer) +{ + return Livewire::actingAs($viewer)->test(Sheet::class, ['campaign' => $character->campaign, 'character' => $character]); +} + +it('offers no sheet on a system-agnostic campaign', function () { + $campaign = Campaign::factory()->create(['ruleset' => Ruleset::Generic]); + $player = memberOf($campaign, CampaignRole::Player); + $pc = Entity::factory()->for($campaign)->pcOf($player)->forPlayers()->withRecord('Rogue', 5, null)->create(['name' => 'Wren Ashgrove', 'slug' => 'wren-ashgrove']); + + Livewire::actingAs($player) + ->test(EntityShow::class, ['campaign' => $campaign, 'type' => 'characters', 'slug' => $pc->slug]) + ->assertOk() + ->assertDontSee('Character sheet') + ->assertDontSeeLivewire(Sheet::class); + + Livewire::actingAs($player) + ->test(Sheet::class, ['campaign' => $campaign, 'character' => $pc]) + ->assertNotFound(); +}); + +it('lets a player write their own sheet, and reads the maths from it', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aTableOnFifthEdition(); + + Livewire::actingAs($tobin) + ->test(EntityShow::class, ['campaign' => $campaign, 'type' => 'characters', 'slug' => $wren->slug]) + ->assertSee('Character sheet') + ->assertSeeLivewire(Sheet::class); + + $component = sheetOf($wren, $tobin) + ->assertSee('No sheet yet') + ->call('edit') + ->set('scores', ['str' => 10, 'dex' => 17, 'con' => 14, 'int' => 12, 'wis' => 14, 'cha' => 8]) + ->set('savingThrows', ['dex', 'int']) + ->set('skills', ['stealth', 'perception', 'sleight_of_hand']) + ->set('expertise', ['stealth']) + ->set('hpMax', '38') + ->set('hpCurrent', '38') + ->set('hpTemp', '0') + ->set('hitDie', '8') + ->set('hitDiceSpent', '0') + ->set('armorClass', '15') + ->set('speed', '30') + ->call('save') + ->assertHasNoErrors() + // Dexterity 17 is +3; Stealth with expertise at level 5 is +3 +6; Perception + // with proficiency is +2 +3; the Dexterity save is +3 +3; passive Perception + // is 10 and the Perception bonus; initiative is the Dexterity modifier. + ->assertSeeInOrder(['Dexterity', '17', '+3']) + ->assertSeeInOrder(['Stealth', '+9']) + ->assertSeeInOrder(['Perception', '+5']) + ->assertSee('Passive Perception') + ->assertSee('15') + ->assertSee('5d8') + ->assertSee('System Reference Document'); + + $sheet = CharacterSheet::query()->where('entity_id', $wren->id)->firstOrFail(); + + expect($sheet->dexterity)->toBe(17) + ->and($sheet->skills)->toBe(['stealth', 'perception', 'sleight_of_hand']) + ->and($sheet->expertise)->toBe(['stealth']) + ->and($sheet->saving_throws)->toBe(['dex', 'int']) + ->and($sheet->hp_max)->toBe(38) + ->and($sheet->hit_die)->toBe(8) + ->and($sheet->skillBonus('stealth'))->toBe(9) + ->and($sheet->skillBonus('athletics'))->toBe(0) + ->and($sheet->saveBonus('dex'))->toBe(6) + ->and($sheet->saveBonus('str'))->toBe(0) + ->and($sheet->passivePerception())->toBe(15) + ->and($sheet->initiative())->toBe(3) + ->and($sheet->proficiencyBonus())->toBe(3); + + // A second save replaces the row rather than adding one. + $component->call('edit')->set('hpMax', '40')->call('save')->assertHasNoErrors(); + + expect(CharacterSheet::query()->where('entity_id', $wren->id)->count())->toBe(1) + ->and($sheet->fresh()->hp_max)->toBe(40); +}); + +it('keeps a player off another character, and lets a GM write on anyone', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'halder' => $halder, 'abbess' => $abbess] = aTableOnFifthEdition(); + + sheetOf($halder, $tobin) + ->assertDontSee('Edit sheet') + ->call('edit') + ->assertForbidden(); + + sheetOf($halder, $tobin)->call('save')->assertForbidden(); + sheetOf($halder, $tobin)->call('damage', 5)->assertForbidden(); + sheetOf($halder, $tobin)->call('longRest')->assertForbidden(); + + sheetOf($abbess, ownerOf($campaign)) + ->call('edit') + ->set('scores', ['str' => 8, 'dex' => 12, 'con' => 12, 'int' => 16, 'wis' => 18, 'cha' => 15]) + ->set('hpMax', '27') + ->set('hpCurrent', '27') + ->set('hitDie', '8') + ->call('save') + ->assertHasNoErrors(); + + expect(CharacterSheet::query()->where('entity_id', $abbess->id)->exists())->toBeTrue() + ->and(CharacterSheet::query()->where('entity_id', $halder->id)->exists())->toBeFalse(); +}); + +it('takes damage off temporary hit points first, and heals no higher than the maximum', function () { + ['tobin' => $tobin, 'wren' => $wren] = aTableOnFifthEdition(); + + $sheet = CharacterSheet::factory()->forCharacter($wren)->create(['hp_max' => 38, 'hp_current' => 38, 'hp_temp' => 5]); + + $component = sheetOf($wren, $tobin)->set('damageAmount', '12')->call('damage')->assertHasNoErrors(); + + expect($sheet->fresh()->hp_temp)->toBe(0) + ->and($sheet->fresh()->hp_current)->toBe(31); + + $component->set('damageAmount', '40')->call('damage'); + + expect($sheet->fresh()->hp_current)->toBe(0); + + $component->set('healAmount', '10')->call('heal'); + + expect($sheet->fresh()->hp_current)->toBe(10); + + $component->set('healAmount', '100')->call('heal'); + + expect($sheet->fresh()->hp_current)->toBe(38); + + $component->set('damageAmount', '0')->call('damage')->assertHasErrors('damageAmount'); + + app(AdjustHitPoints::class)->damage($sheet->fresh(), 3); + + expect($sheet->fresh()->hp_current)->toBe(35); +}); + +it('makes the sheet whole on a long rest', function () { + ['tobin' => $tobin, 'wren' => $wren] = aTableOnFifthEdition(); + + $sheet = CharacterSheet::factory()->forCharacter($wren)->create([ + 'hp_max' => 38, + 'hp_current' => 10, + 'hp_temp' => 3, + 'hit_dice_spent' => 4, + 'spell_slots' => [1 => ['total' => 4, 'used' => 3], 2 => ['total' => 2, 'used' => 2]], + ]); + + sheetOf($wren, $tobin)->call('longRest')->assertHasNoErrors(); + + $rested = $sheet->fresh(); + + expect($rested->hp_current)->toBe(38) + ->and($rested->hp_temp)->toBe(0) + // Half of five hit dice, rounded down: two come back. + ->and($rested->hit_dice_spent)->toBe(2) + ->and($rested->spell_slots)->toBe([1 => ['total' => 4, 'used' => 0], 2 => ['total' => 2, 'used' => 0]]); + + app(LongRest::class)->handle($rested); + + expect($rested->fresh()->hit_dice_spent)->toBe(0); +}); + +it('refuses a score outside the bounds, a hit die the rules do not have, and a skill it does not know', function () { + ['tobin' => $tobin, 'wren' => $wren] = aTableOnFifthEdition(); + + sheetOf($wren, $tobin) + ->call('edit') + ->set('scores', ['str' => 31, 'dex' => 0, 'con' => 14, 'int' => 12, 'wis' => 14, 'cha' => 8]) + ->set('hitDie', '7') + ->set('skills', ['stealth', 'lockpicking']) + ->set('hpMax', '38') + ->set('hpCurrent', '50') + ->call('save') + ->assertHasErrors(['scores.str', 'scores.dex', 'hitDie', 'skills.1', 'hpCurrent']); + + expect(CharacterSheet::query()->where('entity_id', $wren->id)->exists())->toBeFalse(); +}); + +it('shows the party pack on the sheet, and is read by whoever may read the character', function () { + ['campaign' => $campaign, 'mira' => $mira, 'wren' => $wren] = aTableOnFifthEdition(); + + CharacterSheet::factory()->forCharacter($wren)->create(['dexterity' => 17]); + LedgerEntry::factory()->inCampaign($campaign)->item('Tidewarden Signet', 1)->create(); + + sheetOf($wren, $mira) + ->assertSee('Tidewarden Signet') + ->assertSeeInOrder(['Dexterity', '17']) + ->assertDontSee('Edit sheet') + ->assertDontSee('Long rest'); +}); + +it('travels nested under its character, lands in the vault, and shows in the API', function () { + ['campaign' => $campaign, 'tobin' => $tobin, 'wren' => $wren] = aTableOnFifthEdition(); + + CharacterSheet::factory()->forCharacter($wren)->create([ + 'dexterity' => 17, + 'skills' => ['stealth'], + 'expertise' => ['stealth'], + 'hp_max' => 38, + 'hp_current' => 20, + 'spell_slots' => [1 => ['total' => 2, 'used' => 1]], + ]); + + $document = exportedArray($campaign); + $wrenRow = collect($document['entities'])->firstWhere('slug', 'wren-ashgrove'); + $halderRow = collect($document['entities'])->firstWhere('slug', 'halder-bream'); + + expect($wrenRow['sheet']['dexterity'])->toBe(17) + ->and($wrenRow['sheet']['skills'])->toBe(['stealth']) + ->and($wrenRow['sheet']['spell_slots'])->toBe(['1' => ['total' => 2, 'used' => 1]]) + ->and($halderRow['sheet'])->toBeNull(); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeTrue(); + + $copy = app(ImportCampaign::class)->handle($read->document, User::factory()->create()); + $newWren = Entity::withoutGlobalScopes()->where('campaign_id', $copy->id)->where('slug', 'wren-ashgrove')->firstOrFail(); + $copied = CharacterSheet::withoutGlobalScopes()->where('entity_id', $newWren->id)->firstOrFail(); + + expect($copied->dexterity)->toBe(17) + ->and($copied->expertise)->toBe(['stealth']) + ->and($copied->hp_current)->toBe(20) + ->and($copied->spell_slots)->toBe([1 => ['total' => 2, 'used' => 1]]) + ->and(CharacterSheet::withoutGlobalScopes()->where('campaign_id', $copy->id)->count())->toBe(1); + + $vault = app(WriteCampaignMarkdown::class)->handle($campaign)['markdown/characters/wren-ashgrove.md']; + + expect($vault)->toContain('## Character sheet') + ->toContain('Dexterity 17 (+3)') + ->toContain('Hit points: 20 of 38') + ->toContain('Stealth +9'); + + asKey($tobin) + ->getJson("/api/v1/campaigns/{$campaign->id}/entities/{$wren->id}") + ->assertOk() + ->assertJsonPath('data.sheet.scores.dex', 17) + ->assertJsonPath('data.sheet.skills.stealth', 9) + ->assertJsonPath('data.sheet.hit_points.current', 20) + ->assertJsonPath('data.sheet.proficiency_bonus', 3); +}); + +it('refuses a file whose sheet carries a score outside the bounds', function () { + ['campaign' => $campaign, 'wren' => $wren] = aTableOnFifthEdition(); + + CharacterSheet::factory()->forCharacter($wren)->create(); + + $document = exportedArray($campaign); + $document['entities'] = array_map(function (array $row): array { + if ($row['slug'] === 'wren-ashgrove') { + $row['sheet']['dexterity'] = 40; + } + + return $row; + }, $document['entities']); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeFalse() + ->and(implode(' ', $read->errors))->toContain('sheet'); +}); + +it('reads an older file whose characters carry no sheet', function () { + ['campaign' => $campaign] = aTableOnFifthEdition(); + + $document = exportedArray($campaign); + $document['entities'] = array_map(function (array $row): array { + unset($row['sheet']); + + return $row; + }, $document['entities']); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeTrue() + ->and(collect($read->document['entities'])->pluck('sheet')->unique()->all())->toBe([null]); +}); diff --git a/tests/Unit/Sheets/FifthEditionTest.php b/tests/Unit/Sheets/FifthEditionTest.php new file mode 100644 index 0000000..fb3378d --- /dev/null +++ b/tests/Unit/Sheets/FifthEditionTest.php @@ -0,0 +1,52 @@ +toBe($modifier); +})->with([ + [1, -5], [8, -1], [9, -1], [10, 0], [11, 0], [12, 1], [17, 3], [20, 5], [30, 10], +]); + +it('reads the proficiency bonus off the level', function (int $level, int $bonus) { + expect(FifthEdition::proficiencyBonus($level))->toBe($bonus); +})->with([ + [1, 2], [4, 2], [5, 3], [8, 3], [9, 4], [12, 4], [13, 5], [16, 5], [17, 6], [20, 6], + // A character with no level yet computes at level 1. + [0, 2], +]); + +it('adds the proficiency bonus once for a proficiency and twice for expertise', function () { + expect(FifthEdition::skillBonus(17, false, false, 5))->toBe(3) + ->and(FifthEdition::skillBonus(17, true, false, 5))->toBe(6) + ->and(FifthEdition::skillBonus(17, true, true, 5))->toBe(9) + // Expertise without proficiency is a form mistake, and it reads as proficiency. + ->and(FifthEdition::skillBonus(17, false, true, 5))->toBe(6) + ->and(FifthEdition::saveBonus(14, true, 9))->toBe(6) + ->and(FifthEdition::saveBonus(14, false, 9))->toBe(2); +}); + +it('prints a bonus with its sign', function () { + expect(FifthEdition::signed(3))->toBe('+3') + ->and(FifthEdition::signed(-1))->toBe('-1') + ->and(FifthEdition::signed(0))->toBe('+0'); +}); + +it('gives back half the hit dice on a long rest, and at least one', function () { + expect(FifthEdition::hitDiceAfterLongRest(5, 5))->toBe(3) + ->and(FifthEdition::hitDiceAfterLongRest(1, 1))->toBe(0) + ->and(FifthEdition::hitDiceAfterLongRest(0, 5))->toBe(0) + ->and(FifthEdition::hitDiceAfterLongRest(9, 9))->toBe(5); +}); + +it('knows eighteen skills, each on one of the six abilities', function () { + expect(FifthEdition::SKILLS)->toHaveCount(18) + ->and(FifthEdition::ABILITIES)->toHaveCount(6) + ->and(collect(FifthEdition::SKILLS)->pluck('ability')->unique()->diff(array_keys(FifthEdition::ABILITIES))->all())->toBe([]) + ->and(FifthEdition::SKILLS['stealth'])->toBe(['name' => 'Stealth', 'ability' => 'dex']) + ->and(FifthEdition::SKILLS['sleight_of_hand']['name'])->toBe('Sleight of Hand'); +});