]> git.localhorst.tv Git - l2e.git/blob - src/common/Inventory.cpp
275de538f49f83eb344b549d55f1b41fad81f10f
[l2e.git] / src / common / Inventory.cpp
1 /*
2  * Inventory.cpp
3  *
4  *  Created on: Aug 9, 2012
5  *      Author: holy
6  */
7
8 #include "Inventory.h"
9
10 #include "Item.h"
11
12 #include <algorithm>
13
14
15 namespace common {
16
17 Inventory::Inventory()
18 : scenarioEnd(0) {
19
20 }
21
22 bool Inventory::Add(const Item *item, int count) {
23         if (count > 99) return false;
24
25         Entry *entry(FindItem(item));
26         if (entry) {
27                 if (entry->count + count > 99) {
28                         return false;
29                 } else {
30                         entry->count += count;
31                         return true;
32                 }
33         } else {
34                 for (int i(0); i < MaxItems(); ++i) {
35                         if (SloteFree(i)) {
36                                 entries[i].item = item;
37                                 entries[i].count = count;
38                                 return true;
39                         }
40                 }
41                 return false;
42         }
43 }
44
45 void Inventory::Remove(const Item *item, int count) {
46         Entry *entry(FindItem(item));
47         if (!entry) return;
48
49         if (entry->count <= count) {
50                 entry->item = 0;
51                 entry->count = 0;
52         } else {
53                 entry->count -= count;
54         }
55 }
56
57 void Inventory::RemoveAll(const Item *item) {
58         Remove(item, 255);
59 }
60
61 Inventory::Entry *Inventory::FindItem(const Item *item) {
62         for (int i(0); i < MaxItems(); ++i) {
63                 if (item == ItemAt(i)) {
64                         return entries + i;
65                 }
66         }
67         return 0;
68 }
69
70 bool Inventory::SloteFree(int offset) const {
71         return !ItemAt(offset);
72 }
73
74
75 bool Inventory::AddScenarioItem(const Item *i) {
76         if (scenarioEnd < MaxScenarioItems()) {
77                 scenario[scenarioEnd] = i;
78                 ++scenarioEnd;
79                 return true;
80         } else {
81                 return false;
82         }
83 }
84
85
86 void Inventory::Sort() {
87         std::sort(entries, entries + 96, Entry::Less);
88 }
89
90 bool Inventory::Entry::Less(const Entry &lhs, const Entry &rhs) {
91         if (lhs.item) {
92                 if (rhs.item) {
93                         return Item::Less(*lhs.item, *rhs.item);
94                 } else {
95                         return true;
96                 }
97         } else {
98                 return false;
99         }
100 }
101
102 void Inventory::SwapEntriesAt(int lhs, int rhs) {
103         std::swap(entries[lhs], entries[rhs]);
104 }
105
106 }