]> git.localhorst.tv Git - l2e.git/blob - src/common/Inventory.cpp
implemented inventory item swapping
[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 Inventory::Entry *Inventory::FindItem(const Item *item) {
57         for (int i(0); i < MaxItems(); ++i) {
58                 if (item == ItemAt(i)) {
59                         return entries + i;
60                 }
61         }
62         return 0;
63 }
64
65 bool Inventory::SloteFree(int offset) const {
66         return !ItemAt(offset);
67 }
68
69
70 void Inventory::Sort() {
71         std::sort(entries, entries + 96, Entry::Less);
72 }
73
74 bool Inventory::Entry::Less(const Entry &lhs, const Entry &rhs) {
75         if (lhs.item) {
76                 if (rhs.item) {
77                         return Item::Less(*lhs.item, *rhs.item);
78                 } else {
79                         return true;
80                 }
81         } else {
82                 return false;
83         }
84 }
85
86 void Inventory::SwapEntriesAt(int lhs, int rhs) {
87         std::swap(entries[lhs], entries[rhs]);
88 }
89
90 }