inventory #14

Merged
erns6604 merged 11 commits from inventory into main 2025-10-29 14:21:29 +01:00
3 changed files with 60 additions and 6 deletions
Showing only changes of commit 6d4d99d240 - Show all commits

View File

@@ -6,6 +6,7 @@ import Item.ItemStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
public class Inventory {
private final List<ItemStack> items;
@@ -25,12 +26,44 @@ public class Inventory {
return Collections.unmodifiableList(items);
}
public void addItem(ItemStack item) {
int totalWeight = calculateStackWeight(item);
if (totalWeight > weightLimit) {
return;
public void addItem(ItemStack stack) {
boolean isSingleItem = stack.getQuantity() == 1;
if (isSingleItem) {
if(stack.getItem().getWeight() > weightLimit) return;
items.add(stack);
}
items.add(item);
if (stack.getWeight() + getCurrentWeight() > weightLimit) addSubStack(stack);
items.add(stack);
}
private void addSubStack(ItemStack stack) {
int maxQuantity = calculateMaxQuantity(stack);
items.add(new ItemStack(stack.getItem(), maxQuantity));
}
private int calculateMaxQuantity(ItemStack stack) {
int maxQuantity = 1;
int weight = stack.getItem().getWeight();
for (int i = maxQuantity; i <= stack.getQuantity(); i++) {
int currentWeightWithStack = (weight * maxQuantity) + getCurrentWeight();
boolean weightOutsideLimits = currentWeightWithStack >= weightLimit;
if (weightOutsideLimits) {
break;
} else {
maxQuantity++;
}
}
return maxQuantity;
}
private int getCurrentWeight() {
int currentWeight = 0;
for (ItemStack item : items) {
currentWeight += item.getItem().getWeight();
}
return currentWeight;
}
private int calculateStackWeight(ItemStack stack) {

View File

@@ -13,4 +13,8 @@ public record ItemStack(Item item, int quantity) {
public int getQuantity() {
return quantity;
}
public int getWeight() {
return item.getWeight() * quantity;
}
}

View File

@@ -35,7 +35,7 @@ public class InventoryTest {
}
@Test
void item_can_not_be_added_if_it_exeeds_weight_limit() {
void item_can_not_be_added_if_above_weight_limit() {
var inventory = new Inventory(5);
var item = new BasicItem("iron_sword", "Iron Sword", 10);
var stack = new ItemStack(item, 1);
@@ -43,4 +43,21 @@ public class InventoryTest {
assertThat(inventory.getItems().size(), is(0));
}
@Test
void stack_can_be_added_up_to_capacity() {
var inventory = new Inventory(5);
var item = new BasicItem("sand_grain", "Sand Grain", 1);
var stack = new ItemStack(item, 8);
inventory.addItem(stack);
assertThat(inventory.getItems(), hasItem(allOf(
hasProperty("item", (
hasProperty("id", equalTo("sand_grain"))
)),
hasProperty("quantity", equalTo(5)))
));
}
}