Skip to content

Instantly share code, notes, and snippets.

@Johni0702
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Johni0702/66d70791524e20973835 to your computer and use it in GitHub Desktop.
Save Johni0702/66d70791524e20973835 to your computer and use it in GitHub Desktop.
public void shiftClick(GlowPlayer player, InventoryView view, int clickedSlot, ItemStack clickedItem) {
// try to fill partial, then empty stacks
// first main inventory then hotbar
clickedItem = tryToFillSlots(clickedItem, player.getInventory(), 9, 36, 0, 9);
view.setItem(clickedSlot, clickedItem);
}
public static ItemStack tryToFillSlots(ItemStack stack, GlowInventory target, int...slots) {
if (slots.length % 2 != 0) {
throw new IllegalArgumentException("Slots must be pairs.");
}
// First empty slot, -1 if no empty slot was found yet
int firstEmpty = -1;
for (int s = 0; s < slots.length && stack.getAmount() > 0; s+=2) {
// Iterate through all pairs of start and end slots
int start = slots[s];
int end = slots[s+1];
int delta = start < end ? 1 : -1;
for (int i = start; i != end && stack.getAmount() > 0; i += delta) {
// Check whether shift clicking is allowed in that slot of the inventory
if (!target.itemShiftClickAllowed(slot, stack)) {
continue;
}
ItemStack currentStack = target.getItem(i);
if (currentStack == null) {
if (firstEmpty == -1) {
firstEmpty = i; // Found first empty slot
}
} else {
tryToFillSlot(stack, currentStack, target, i); // Non empty slot, try to fill stack
}
}
}
if (stack.getAmount() <= 0) {
stack = null;
}
if (stack != null && firstEmpty != -1) {
target.setItem(firstEmpty, stack);
stack = null;
}
return stack;
}
private static ItemStack tryToFillSlot(ItemStack stack, ItemStack currentStack, GlowInventory target, int slot) {
if (currentStack.isSimilar(stack)) {
// If current item and new item are similar, calculate the amount of transferable items
int amount = currentStack.getAmount();
int maxStackSize = Math.min(currentStack.getMaxStackSize(), target.getMaxStackSize());
int transfer = Math.min(stack.getAmount(), maxStackSize - amount);
if (transfer > 0) {
// And if there are any, transfer them
currentStack.setAmount(amount + transfer);
stack.setAmount(stack.getAmount() - transfer);
}
target.setItem(slot, currentStack);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment