-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInventory.java
68 lines (55 loc) · 1.6 KB
/
Inventory.java
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
package model.farm;
import model.farm.data.item.Item;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class Inventory implements Serializable {
private final Map<Item, Integer> items;
private int capacity;
private int occupied;
public Inventory() {
this(0);
}
public Inventory(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Negative capacity");
this.capacity = capacity;
this.occupied = 0;
this.items = new HashMap<>();
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getCapacity() {
return this.capacity;
}
public int getOccupied() {
return this.occupied;
}
public int getAmount(Item item) {
Integer amount = this.items.get(item);
if (amount == null) {
return 0;
} else {
return amount;
}
}
public void storeItem(Item item, int amount) {
// Discards items that can't be stored
if (this.occupied + amount > this.capacity) {
amount = this.capacity - this.occupied;
}
this.occupied += amount;
this.items.put(item, getAmount(item) + amount);
}
public int removeItem(Item item, int amount) {
int currentAmount = getAmount(item);
if (amount >= currentAmount) {
amount = currentAmount;
this.items.remove(item);
} else {
this.items.put(item, currentAmount - amount);
}
this.occupied -= amount;
return amount;
}
}