From 8f375a38ad972a1fcac7953cc0d254313c88b7c9 Mon Sep 17 00:00:00 2001 From: Björn Steinbrink Date: Wed, 8 Mar 2006 03:21:05 +0000 Subject: Made Inventory use STL algorithms and fixed getLastUsedSlot semantics. --- src/inventory.cpp | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) (limited to 'src/inventory.cpp') diff --git a/src/inventory.cpp b/src/inventory.cpp index 65f21292..0467df10 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -23,8 +23,17 @@ #include "inventory.h" +#include + #include "item.h" +struct SlotUsed : public std::unary_function +{ + bool operator()(const Item &item) const { + return (item.getId() != -1 && item.getQuantity() > 0); + } +}; + Inventory::Inventory() { mItems = new Item[INVENTORY_SIZE]; @@ -76,6 +85,7 @@ void Inventory::removeItem(int id) if (mItems[i].getId() == id) { mItems[i].setId(-1); mItems[i].setQuantity(0); + mItems[i].setEquipped(false); } } } @@ -93,37 +103,23 @@ bool Inventory::contains(Item *item) int Inventory::getFreeSlot() { - for (int i = 2; i < INVENTORY_SIZE; i++) { - if (mItems[i].getId() == -1) { - return i; - } - } - return -1; + Item *i = std::find_if(mItems + 2, mItems + INVENTORY_SIZE, + std::not1(SlotUsed())); + return (i == mItems + INVENTORY_SIZE) ? -1 : (i - mItems); } int Inventory::getNumberOfSlotsUsed() { - int numberOfFilledSlot = 0; - for (int i = 0; i < INVENTORY_SIZE; i++) - { - if (mItems[i].getId() > -1 || mItems[i].getQuantity() > 0) - { - numberOfFilledSlot++; - } - } - - return numberOfFilledSlot; + return count_if(mItems, mItems + INVENTORY_SIZE, SlotUsed()); } int Inventory::getLastUsedSlot() { - int i; - - for (i = INVENTORY_SIZE - 1; i >= 0; i--) { - if ((mItems[i].getId() != -1) && (mItems[i].getQuantity() > 0)) { - break; + for (int i = INVENTORY_SIZE - 1; i >= 0; i--) { + if (SlotUsed()(mItems[i])) { + return i; } } - return --i; + return -1; } -- cgit v1.2.3-70-g09d2