From b56a1d76450f0633cdb78aa72c8eb3dd642382da Mon Sep 17 00:00:00 2001 From: Major- Date: Fri, 14 Feb 2014 23:30:43 +0000 Subject: [PATCH] Add utility methods to Inventory. --- src/org/apollo/game/model/Inventory.java | 60 ++++++++++++++++++++---- 1 file changed, 51 insertions(+), 9 deletions(-) diff --git a/src/org/apollo/game/model/Inventory.java b/src/org/apollo/game/model/Inventory.java index c4a2c3b2..e66b0a16 100644 --- a/src/org/apollo/game/model/Inventory.java +++ b/src/org/apollo/game/model/Inventory.java @@ -251,13 +251,7 @@ public final class Inventory implements Cloneable { * @return {@code true} if so, {@code false} if not. */ public boolean contains(int id) { - for (int i = 0; i < capacity; i++) { - Item item = items[i]; - if (item != null && item.getId() == id) { - return true; - } - } - return false; + return slotOf(id) != -1; } /** @@ -303,6 +297,34 @@ public final class Inventory implements Cloneable { return items[slot]; } + /** + * Gets the amount of items with the specified id in this inventory. + * + * @param id The id. + * @return The number of matching items, or {@code 0} if none were found. + */ + public int getAmount(int id) { + if (isStackable(ItemDefinition.lookup(id))) { + int slot = slotOf(id); + if (slot != -1) { + return items[slot].getAmount(); + } + return 0; + } + + int amount = 0, usedSlots = 0; + for (int i = 0; i < capacity && usedSlots <= size; i++) { + Item item = items[i]; + if (item != null) { + if (item.getId() == id) { + amount++; + } + usedSlots++; + } + } + return amount; + } + /** * Gets a clone of the items array. * @@ -382,8 +404,8 @@ public final class Inventory implements Cloneable { * @return The amount that was removed. */ public int remove(int id, int amount) { - ItemDefinition def = ItemDefinition.lookup(id); - boolean stackable = isStackable(def); + ItemDefinition definition = ItemDefinition.lookup(id); + boolean stackable = isStackable(definition); if (stackable) { for (int slot = 0; slot < capacity; slot++) { Item item = items[slot]; @@ -505,6 +527,26 @@ public final class Inventory implements Cloneable { return size; } + /** + * Gets the inventory slot for the specified id. + * + * @param id The id. + * @return The first slot containing the specified item, or {@code -1} if none of the slots matched the conditions. + */ + public int slotOf(int id) { + int usedSlots = 0; + for (int slot = 0; slot < capacity && usedSlots <= size; slot++) { + Item item = items[slot]; + if (item != null) { + if (item.getId() == id) { + return slot; + } + usedSlots++; + } + } + return -1; + } + /** * Starts the firing of events. */