8000 fix(inventory): recompute equipped armor class by Mnehmos · Pull Request #89 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 51 additions & 45 deletions src/server/consolidated/inventory-manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,45 @@ function ensureDb() {
};
}

/**
* Rebuild AC from the character's currently equipped armor instead of
* incrementally adding/subtracting bonuses. Older starter items persisted
* their armor base as `ac`; newer/authored items may use `baseAC`.
*/
function equippedArmorClass(
dexterity: number,
items: ReturnType<InventoryRepository['getInventoryWithDetails']>['items']
): number {
const dexMod = Math.floor((dexterity - 10) / 2);
let armorBase = 10 + dexMod;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the character's authoritative AC baseline

When a character's AC comes from an explicit character_manage.create value, natural armor, or another feature not represented by an inventory item, initializing the calculation to 10 + DEX discards that AC. Because both equip and unequip now invoke this helper unconditionally, merely equipping an ordinary weapon can change an AC 18 character to 10–12 even though no armor changed; the recomputation needs to preserve non-equipment AC or run only when the complete AC basis is represented by equipped items.

Useful? React with 👍 / 👎.

let equipmentBonus = 0;

for (const entry of items) {
if (!entry.equipped || !entry.item.properties) continue;
const props = entry.item.properties as Record<string, unknown>;
if (typeof props.acBonus === 'number') equipmentBonus += props.acBonus;

const baseAC = typeof props.baseAC === 'number'
? props.baseAC
: typeof props.ac === 'number'
? props.ac
: null;
if (baseAC === null || entry.slot !== 'armor') continue;

// Legacy heavy starter armor has no explicit maxDexBonus, but does
// carry a Strength requirement. Heavy armor never adds Dexterity.
const maxDexBonus = typeof props.maxDexBonus === 'number'
? props.maxDexBonus
: typeof props.strengthRequired === 'number'
? 0
: Number.POSITIVE_INFINITY;
const dexContribution = maxDexBonus === 0 ? 0 : Math.min(dexMod, maxDexBonus);
armorBase = Math.max(armorBase, baseAC + dexContribution);
}

return armorBase + equipmentBonus;
}

// ═══════════════════════════════════════════════════════════════════════════
// ACTION SCHEMAS
// ═══════════════════════════════════════════════════════════════════════════
Expand Down Expand Up @@ -295,30 +334,15 @@ const definitions: Record<InventoryAction, ActionDefinition> = {

inventoryRepo.equipItem(params.characterId, params.itemId, params.slot);

// Update character AC if item has AC properties
// Rebuild AC from all equipped items. This supports legacy starter
// armor (`properties.ac`) and avoids bonus drift after replacements.
const character = charRepo.findById(params.characterId);
let acChange: string | null = null;

if (character && item.properties) {
const props = item.properties as Record<string, unknown>;
let newAc = character.ac;

if (props.acBonus && typeof props.acBonus === 'number') {
newAc = character.ac + props.acBonus;
acChange = `AC increased by ${props.acBonus} (now ${newAc})`;
}

if (props.baseAC && typeof props.baseAC === 'number' && params.slot === 'armor') {
const dexMod = Math.floor((character.stats.dex - 10) / 2);
const maxDexBonus = props.maxDexBonus !== undefined ? Number(props.maxDexBonus) : 99;
const effectiveDexBonus = Math.min(dexMod, maxDexBonus);
newAc = props.baseAC + (maxDexBonus > 0 ? effectiveDexBonus : 0);
acChange = `AC set to ${newAc} (base ${props.baseAC}${maxDexBonus < 99 ? ` + DEX max ${maxDexBonus}` : ' + DEX'})`;
}

if (newAc !== character.ac) {
charRepo.update(params.characterId, { ac: newAc });
}
if (character) {
const newAc = equippedArmorClass(character.stats.dex, inventoryRepo.getInventoryWithDetails(params.characterId).items);
if (newAc !== character.ac) charRepo.update(params.characterId, { ac: newAc });
acChange = `AC recalculated from equipped armor (now ${newAc})`;
}

return {
Expand All @@ -340,36 +364,18 @@ const definitions: Record<InventoryAction, ActionDefinition> = {
const { inventoryRepo, itemRepo, charRepo } = ensureDb();

const item = itemRepo.findById(params.itemId);
const inventory = inventoryRepo.getInventory(params.characterId);
const equippedItem = inventory.items.find((i: { itemId: string; equipped: boolean }) =>
i.itemId === params.itemId && i.equipped
);
const slot = equippedItem?.slot;

inventoryRepo.unequipItem(params.characterId, params.itemId);

// Update character AC
// Rebuild AC after removing the item so remaining armor and shield
// bonuses stay authoritative.
const character = charRepo.findById(params.characterId);
let acChange: string | null = null;

if (character && item?.properties) {
const props = item.properties as Record<string, unknown>;
let newAc = character.ac;

if (props.acBonus && typeof props.acBonus === 'number') {
newAc = Math.max(10, character.ac - props.acBonus);
acChange = `AC decreased by ${props.acBonus} (now ${newAc})`;
}

if (props.baseAC && typeof props.baseAC === 'number' && slot === 'armor') {
const dexMod = Math.floor((character.stats.dex - 10) / 2);
newAc = 10 + dexMod;
acChange = `AC reverted to unarmored (${newAc})`;
}

if (newAc !== character.ac) {
charRepo.update(params.characterId, { ac: newAc });
}
if (character) {
const newAc = equippedArmorClass(character.stats.dex, inventoryRepo.getInventoryWithDetails(params.characterId).items);
if (newAc !== character.ac) charRepo.update(params.characterId, { ac: newAc });
acChange = `AC recalculated from equipped armor (now ${newAc})`;
}

return {
Expand Down
54 changes: 54 additions & 0 deletions tests/server/consolidated/inventory-manage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,60 @@ describe('inventory_manage consolidated tool', () => {
expect(data.slot).toBe('mainhand');
});

it('should recompute legacy starter armor and shield AC as equipment changes', async () => {
const armorResult = await handleItemManage({
action: 'create',
name: 'Chain Mail',
type: 'armor',
weight: 55,
value: 75,
properties: { ac: 16, stealthDisadvantage: true, strengthRequired: 13 }
}, ctx);
const armorId = parseItemResult(armorResult).item.id;
await handleInventoryManage({ action: 'give', characterId: testCharId, itemId: armorId, quantity: 1 }, ctx);

const equipped = parseResult(await handleInventoryManage({
action: 'equip',
characterId: testCharId,
itemId: armorId,
slot: 'armor'
}, ctx));

expect(equipped.success).toBe(true);
expect(equipped.acChange).toContain('now 16');
expect(new CharacterRepository(getDb(':memory:')).findById(testCharId)?.ac).toBe(16);

const shieldResult = await handleItemManage({
action: 'create',
name: 'Shield',
type: 'armor',
weight: 6,
value: 10,
properties: { acBonus: 2 }
}, ctx);
const shieldId = parseItemResult(shieldResult).item.id;
await handleInventoryManage({ action: 'give', characterId: testCharId, itemId: shieldId, quantity: 1 }, ctx);
const shieldEquipped = parseResult(await handleInventoryManage({
action: 'equip',
characterId: testCharId,
itemId: shieldId,
slot: 'offhand'
}, ctx));

expect(shieldEquipped.acChange).toContain('now 18');
expect(new CharacterRepository(getDb(':memory:')).findById(testCharId)?.ac).toBe(18);

const unequipped = parseResult(await handleInventoryManage({
action: 'unequip',
characterId: testCharId,
itemId: armorId
}, ctx));

expect(unequipped.success).toBe(true);
expect(unequipped.acChange).toContain('now 13');
expect(new CharacterRepository(getDb(':memory:')).findById(testCharId)?.ac).toBe(13);
});

it('should accept "wield" alias', async () => {
const result = await handleInventoryManage({
action: 'wield',
Expand Down
Loading
0