Created
July 6, 2022 18:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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