Skip to content

Instantly share code, notes, and snippets.

@reoseah
Created February 10, 2020 00:41
Show Gist options
  • Save reoseah/bc5bfbb41effdf057bf287f6ba54e51e to your computer and use it in GitHub Desktop.
Save reoseah/bc5bfbb41effdf057bf287f6ba54e51e to your computer and use it in GitHub Desktop.
/**
* Checks whether all of given items can be inserted into an inventory.
*/
public static <T extends ItemInventory & ItemInsertable> boolean canInsertAll(List<ItemStack> stacks, T inventory) {
if (stacks.size() == 0) {
return true;
}
if (stacks.size() == 1) {
return inventory.canInsertFully(stacks.get(0));
}
OverlayItemInventory<T> overlay = new OverlayItemInventory<T>(inventory);
for (ItemStack stack : stacks) {
ItemStack excess = overlay.insert(stack, ActionMode.CHANGE);
if (!excess.isEmpty()) {
return false;
}
}
return true;
}
public class OverlayItemInventory<T extends ItemInventory & ItemInsertable> implements ItemInventory, ItemInsertable {
protected final T inventory;
protected final ItemStack[] overlay;
public OverlayItemInventory(T inventory) {
this.inventory = inventory;
this.overlay = new ItemStack[inventory.size()];
}
@Override
public int size() {
return inventory.size();
}
@Override
public ItemStack get(int slot) {
if (overlay[slot] != null) {
return overlay[slot];
}
return inventory.get(slot);
}
@Override
public boolean isValid(int slot, ItemStack stack) {
return inventory.isValid(slot, stack);
}
@Override
public boolean set(int slot, ItemStack stack, ActionMode mode) {
if (!isValid(slot, stack)) {
return false;
}
if (mode == ActionMode.CHANGE) {
overlay[slot] = stack;
}
return true;
}
@Override
public ItemStack insert(ItemStack stack, ActionMode mode) {
return InventoryUtil.insertSequentially(this, stack, mode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment