-
Notifications
You must be signed in to change notification settings - Fork 0
/
Container.cpp
110 lines (103 loc) · 2.25 KB
/
Container.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "Container.h"
#include "ObjectTracker.h"
#include <iostream>
#include <algorithm>
bool Container::addItem(int id, int quant)
{
if (contained.size() == maxItems) {
return false;
}
bool alreadyContained = false;
unsigned n;
for (n = 0; n < contained.size(); n++) {
if (contained.at(n)->id_() == id) {
alreadyContained = true;
break;
}
}
if (alreadyContained) {
quantities.at(n)++;
}
else {
Item* toAdd = tracker->getItem(id);
contained.push_back(toAdd);
quantities.push_back(quant);
}
return true;
}
std::string Container::peekItem(int index)
{
if (index < 0 || (unsigned)index >= contained.size()) {
return "container index out of bounds";
}
std::string result = contained.at(index)->stringRep();
result += "\nQuantity: " + std::to_string(quantities.at(index)) + "\n";
result += util::divider();
return result;
}
Item* Container::viewItem(int index)
{
if (index < 0 || index >= contained.size()) {
return nullptr;
}
return contained.at(index);
}
Item* Container::removeItem(int itemid, int quant)
{
Item* toRemove = tracker->getItem(itemid);
bool found = false;
unsigned n;
for (n = 0; n < contained.size(); n++) {
if (contained.at(n)->id_() == itemid) {
found = true;
break;
}
}
if (found != true) {
return nullptr;
}
if (quant == -1) {
contained.erase(contained.begin() + n);
quantities.erase(quantities.begin() + n);
}
else {
quantities.at(n)--;
if (quantities.at(n) <= 0) {
contained.erase(contained.begin() + n);
quantities.erase(quantities.begin() + n);
}
}
return toRemove;
}
bool Container::moveItemTo(int itemid, Container* newContainer, int quant)
{
int itemIndex = -1;
for (unsigned n = 0; n < contained.size(); n++) {
if (contained.at(n)->id_() == itemid) {
itemIndex = n;
}
}
if (itemIndex == -1) {
return false;
}
if (quant == -1) {
bool check = newContainer->addItem(itemid, quantities.at(itemIndex));
if (check) {
removeItem(itemid, -1);
return true;
}
else {
return false;
}
}
else {
bool check = newContainer->addItem(itemid, quant);
if (check) {
removeItem(itemid, quant);
return true;
}
else {
return false;
}
}
}