Mickey noticed a bug in the code, from the changes in Lesson 10.2, adding a GroupedInventory property for LivingEntity.
When we try to remove multiple items, like when completing a quest, it only removed one item. This lesson will fix the bug.
Step 1: Modify Engine\Models\LivingEntity.cs
There is a problem getting the “groupedInventoryItemToRemove” object on lines 147-148.
For unique items, we want to get the item that exactly matches the parameter. If a player has multiple swords (which will be unique items), we want to get the exact item, and remove it.
For non-unique items, we only need to get the GroupedInventory object with an ItemTypeID that matches the parameter’s ItemTypeID.
So, change lines 147-148 to this:
GroupedInventoryItem groupedInventoryItemToRemove = item.IsUnique ?
GroupedInventory.FirstOrDefault(gi => gi.Item == item) :
GroupedInventory.FirstOrDefault(gi => gi.Item.ItemTypeID == item.ItemTypeID);
This is a “ternary operator“. It evaluates the calculation before the question mark. If that calculation is “true”, it returns the first result (the part before the “:”). If it is “false”, it returns the second result (the part after the “:”).
It’s another way to do a simple “if…else” statement.
So, if the passed-in object is unique, we will look for the first item that completely matches it. If it is not unique, we will find the first item with the same ItemTypeID.
Summary
We really should have unit tests for this project. So, after I finish this batch of refactoring lessons, I’ll start creating those.
NEXT LESSON: Lesson 10.5: Encapsulating Level and ExperiencePoints Properties
PREVIOUS LESSON: Lesson 10.3: Refactoring – Encapsulating LivingEntity Properties (Hit Points and Gold)