Skip to content

Instantly share code, notes, and snippets.

@WizardlyBump17
Created July 6, 2022 18:17
Show Gist options
  • Save WizardlyBump17/585d54fc2d6f6ccb91793ae1be64996b to your computer and use it in GitHub Desktop.
Save WizardlyBump17/585d54fc2d6f6ccb91793ae1be64996b to your computer and use it in GitHub Desktop.
simple method to check if the given items can fully fit in the given inventory
// Method copied from CraftInventory#addItem, but I removed the code that adds items to the inventory
public static boolean canFit(Inventory inventory, ItemStack... items) {
Validate.noNullElements(items, "Item cannot be null");
ItemStack[] inventoryItems = getContents(inventory);
for (ItemStack item : items) {
while (true) {
int firstPartial = firstPartial(inventoryItems, item);
if (firstPartial == -1) {
int firstFree = inventory.firstEmpty();
if (firstFree == -1)
return false;
if (item.getAmount() > inventory.getMaxStackSize()) {
ItemStack stack = item.clone();
stack.setAmount(inventory.getMaxStackSize());
setItem(inventoryItems, firstFree, stack);
item.setAmount(item.getAmount() - inventory.getMaxStackSize());
}
setItem(inventoryItems, firstFree, item);
break;
}
ItemStack partialItem = inventoryItems[firstPartial];
int amount = item.getAmount();
int partialAmount = partialItem.getAmount();
int maxAmount = partialItem.getMaxStackSize();
if (amount + partialAmount <= maxAmount) {
partialItem.setAmount(amount + partialAmount);
setItem(inventoryItems, firstPartial, partialItem);
break;
}
partialItem.setAmount(maxAmount);
setItem(inventoryItems, firstPartial, partialItem);
item.setAmount(amount + partialAmount - maxAmount);
}
}
return true;
}
private static ItemStack[] getContents(Inventory inventory) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++)
items[i] = items[i] == null ? null : items[i].clone();
return items;
}
private static int firstPartial(ItemStack[] items, ItemStack item) {
for (int i = 0; i < items.length; i++) {
ItemStack cItem = items[i];
if (cItem != null && cItem.getAmount() < cItem.getMaxStackSize() && cItem.isSimilar(item))
return i;
}
return -1;
}
private static void setItem(ItemStack[] items, int slot, ItemStack item) {
items[slot] = item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment