]> git.localhorst.tv Git - l2e.git/blob - src/common/Inventory.cpp
made vector components writable
[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
19 }
20
21 bool Inventory::Add(const Item *item, int count) {
22         if (count > 99) return false;
23
24         Entry *entry(FindItem(item));
25         if (entry) {
26                 if (entry->count + count > 99) {
27                         return false;
28                 } else {
29                         entry->count += count;
30                         return true;
31                 }
32         } else {
33                 for (int i(0); i < MaxItems(); ++i) {
34                         if (SloteFree(i)) {
35                                 entries[i].item = item;
36                                 entries[i].count = count;
37                                 return true;
38                         }
39                 }
40                 return false;
41         }
42 }
43
44 void Inventory::Remove(const Item *item, int count) {
45         Entry *entry(FindItem(item));
46         if (!entry) return;
47
48         if (entry->count <= count) {
49                 entry->item = 0;
50                 entry->count = 0;
51         } else {
52                 entry->count -= count;
53         }
54 }
55
56 void Inventory::RemoveAll(const Item *item) {
57         Remove(item, 255);
58 }
59
60 Inventory::Entry *Inventory::FindItem(const Item *item) {
61         for (int i(0); i < MaxItems(); ++i) {
62                 if (item == ItemAt(i)) {
63                         return entries + i;
64                 }
65         }
66         return 0;
67 }
68
69 bool Inventory::SloteFree(int offset) const {
70         return !ItemAt(offset);
71 }
72
73
74 void Inventory::Sort() {
75         std::sort(entries, entries + 96, Entry::Less);
76 }
77
78 bool Inventory::Entry::Less(const Entry &lhs, const Entry &rhs) {
79         if (lhs.item) {
80                 if (rhs.item) {
81                         return Item::Less(*lhs.item, *rhs.item);
82                 } else {
83                         return true;
84                 }
85         } else {
86                 return false;
87         }
88 }
89
90 void Inventory::SwapEntriesAt(int lhs, int rhs) {
91         std::swap(entries[lhs], entries[rhs]);
92 }
93
94 }