So I have a player, and a shop plugin.
The shop tries to give the player 16 WOOL.
If the player has a free 1 to 63 wool (Ofc having another inv space free) my method should return true. However, if the player has only 63 wool and his other spaces full of other materials, method should return false. My problem here is when the player has 1, and 1, and 1 wool item stacks in inv.getContents(), my method will not calculate it correctly.
Here is my code:
public static boolean canStackItemToInventory(Player player, ItemStack item) {
Material type = item.getType();
int amount = item.getAmount();
if (type.equals(Material.BOW)) return false;
PlayerInventory inventory = player.getInventory();
int itemsNumber = 0;
for (ItemStack itemStack : inventory.getContents()) {
if (itemStack.getType()!=type) continue;
if (itemStack.getAmount()==itemStack.getMaxStackSize()) continue;
itemsNumber+=itemStack.getAmount();
}
itemsNumber+=amount;
return itemsNumber <= type.getMaxStackSize();
}
I wrote this function that should return true or false depending on if the player can hold amount
of a material type
. I have not tested, but it should work
public boolean hasFreeSpace(Material type, int amount, Player player) {
PlayerInventory inv = player.getInventory();
//check if the player has any free slots
if(inv.firstEmpty() == -1) {
return false;
}
//we will decrement this until we need no more space
int neededSpace = amount;
//look through each itemstack
for(ItemStack stack : inv.getContents()) {
//check if that type of item is the same
if(stack.getType() != type)
continue;
//how many more items until the stack is full
int untilStackIsFull = stack.getMaxStackSize() - stack.getAmount();
//if the stack is full we will basically be subtracting zero, otherwise we subtract off how much it can hold
neededSpace -= untilStackIsFull;
//if we have all the space needed return true
if(neededSpace <= 0)
return true;
}
return false;
}