How to get the number of empty slots in the player’s inventory?
I’m trying to calculate how many specific items can be given to the player.
I currently have this code.
private Integer calculateMaxItems(Player player, ItemStack itemStack) {
int value = 0;
MainPlayerInventory mainPlayerInventory = player.getInventory().query(QueryOperationTypes.INVENTORY_TYPE.of(MainPlayerInventory.class));
Iterable<Slot> slots = mainPlayerInventory.slots();
for(Slot playerSlot : slots) {
int difference = itemStack.getMaxStackQuantity() - playerSlot.query(QueryOperationTypes.ITEM_STACK_IGNORE_QUANTITY.of(itemStack)).totalItems();
if(playerSlot.totalItems() == 0) {
value = value + itemStack.getMaxStackQuantity();
}
if(playerSlot.contains(itemStack)) {
if(playerSlot.query(QueryOperationTypes.ITEM_STACK_IGNORE_QUANTITY.of(itemStack)).totalItems() != itemStack.getMaxStackQuantity()) {
value = value + difference;
}
}
}
return value;
}
It works, but I would like to know how to do better if possible.
slot.peek().isEmpty()
should be able to tell you whether any specific slot is empty.
I need to consider not full stacks of items.
I found another way to get the allowable amount of items, but this does not work with MainPlayerInventory.
And if I use player.getInventory(), then I also consider my left hand, which is also not acceptable, since I give out items in MainPlayerInventory.
The method consists in accessing the inventory with a request for things of a certain type in it. Next, we calculate the maximum possible volume and subtract from it what the player has. But I can’t correctly get how many items the player has if I check MainPlayerInventory.
I would use this:
Inventory main = player.getInventory().query(QueryOperationTypes.INVENTORY_TYPE.of(MainPlayerInventory.class));
Inventory freeSlots = main.query(QueryOperationTypes.ITEM_STACK_CUSTOM.of(stack -> stack.isEmpty() || stack.getType().equals(DIAMOND)));
int count = freeSlots.capacity() * DIAMOND.getMaxStackQuantity() - freeSlots.totalItems();
Or use 2 queries (one for empty and one for non-empty) and union
the results together.