Java Code Examples for org.bukkit.inventory.ItemStack#setAmount()

The following examples show how to use org.bukkit.inventory.ItemStack#setAmount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InventoryCompressor.java    From Minepacks with GNU General Public License v3.0 6 votes vote down vote up
private void add(ItemStack stack)
{
	if(stack.isSimilar(lastStack) && lastStack.getAmount() < lastStack.getMaxStackSize())
	{ // There is still space on the last stack, try to add it
		int free = lastStack.getMaxStackSize() - lastStack.getAmount();
		int place = Math.min(free, stack.getAmount());
		lastStack.setAmount(lastStack.getAmount()  + place);
		stack.setAmount(stack.getAmount() - place);
	}
	if(stack.getAmount() < 1) return;
	if(filled == targetStacks.length)
	{ // The new item stack is full, add it to overfill list
		toMuch.add(stack);
	}
	else
	{ // Add the rest to the new inventory
		targetStacks[filled++] = stack;
		lastStack = stack;
	}
}
 
Example 2
Source File: CVInventory.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private boolean adjustItemToRemove(ArrayList<ItemStack> itemStacks,
                                Map<Integer, ItemStack> contentsToModify, int i) {
    boolean itemRemoved = false;
    ItemStack currentStack = itemStacks.get(0);
    if (!contentsToModify.containsKey(i)) {
        return false;
    } else if (contentsToModify.get(i).isSimilar(currentStack)) {
        if (contentsToModify.get(i).getAmount() > currentStack.getAmount()) {
            contentsToModify.get(i).setAmount(contentsToModify.get(i).getAmount() - currentStack.getAmount());
            itemStacks.remove(0);
            itemRemoved = true;
        } else if (contentsToModify.get(i).getAmount() < currentStack.getAmount()) {
            int amount = contentsToModify.get(i).getAmount();
            contentsToModify.remove(i);
            currentStack.setAmount(currentStack.getAmount() - amount);
        }
    }
    return itemRemoved;
}
 
Example 3
Source File: ScenarioManager.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public Inventory getScenarioEditInventory(){

        Inventory inv = Bukkit.createInventory(null,6*ROW, Lang.SCENARIO_GLOBAL_INVENTORY_EDIT);

        // add edit item
        ItemStack back = new ItemStack(Material.ARROW);
        ItemMeta itemMeta = back.getItemMeta();
        itemMeta.setDisplayName(Lang.SCENARIO_GLOBAL_ITEM_BACK);
        back.setItemMeta(itemMeta);
        inv.setItem(5*ROW+8,back);

        for (Scenario scenario : Scenario.values()){
            if (!scenario.isCompatibleWithVersion()){
                continue;
            }

            ItemStack scenarioItem = scenario.getScenarioItem();
            if (isActivated(scenario)){
                scenarioItem.addUnsafeEnchantment(Enchantment.DURABILITY, 1);
                scenarioItem.setAmount(2);
            }
            inv.addItem(scenarioItem);
        }

        return inv;
    }
 
Example 4
Source File: ScenarioManager.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public Inventory getScenarioVoteInventory(UhcPlayer uhcPlayer){
    Set<Scenario> playerVotes = uhcPlayer.getScenarioVotes();
    Set<Scenario> blacklist = GameManager.getGameManager().getConfiguration().getScenarioBlackList();
    Inventory inv = Bukkit.createInventory(null,5*ROW, Lang.SCENARIO_GLOBAL_INVENTORY_VOTE);

    for (Scenario scenario : Scenario.values()){
        // Don't add to menu when blacklisted / not compatible / already enabled.
        if (blacklist.contains(scenario) || !scenario.isCompatibleWithVersion() || isActivated(scenario)){
            continue;
        }

        ItemStack item = scenario.getScenarioItem();

        if (playerVotes.contains(scenario)) {
            item.addUnsafeEnchantment(Enchantment.DURABILITY, 1);
            item.setAmount(2);
        }
        inv.addItem(item);
    }
    return inv;
}
 
Example 5
Source File: WoolMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private void refillOneWoolPerContainer() {
  if (!PGM.get().getConfiguration().shouldRefillWool()) return;

  for (Entry<Inventory, Map<Integer, ItemStack>> chest : this.woolChests.entrySet()) {
    Inventory inv = chest.getKey();
    for (Entry<Integer, ItemStack> slotEntry : chest.getValue().entrySet()) {
      int slot = slotEntry.getKey();
      ItemStack wool = slotEntry.getValue();
      ItemStack stack = inv.getItem(slotEntry.getKey());

      if (stack == null) {
        stack = wool.clone();
        stack.setAmount(1);
        inv.setItem(slot, stack);
        break;
      } else if (stack.isSimilar(wool) && stack.getAmount() < wool.getAmount()) {
        stack.setAmount(stack.getAmount() + 1);
        inv.setItem(slot, stack);
        break;
      }
    }
  }
}
 
Example 6
Source File: ItemKeepMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public void restoreKeptInventory(MatchPlayer player) {
  Map<Integer, ItemStack> kept = this.keptInv.remove(player);
  if (kept != null) {
    List<ItemStack> displaced = new ArrayList<>();
    PlayerInventory inv = player.getBukkit().getInventory();

    for (Map.Entry<Integer, ItemStack> entry : kept.entrySet()) {
      int slot = entry.getKey();
      ItemStack keptStack = entry.getValue();
      ItemStack invStack = inv.getItem(slot);

      if (invStack == null) {
        inv.setItem(slot, keptStack);
      } else {
        if (invStack.isSimilar(keptStack)) {
          int n =
              Math.min(keptStack.getAmount(), invStack.getMaxStackSize() - invStack.getAmount());
          invStack.setAmount(invStack.getAmount() + n);
          keptStack.setAmount(keptStack.getAmount() - n);
        }
        if (keptStack.getAmount() > 0) {
          displaced.add(keptStack);
        }
      }
    }

    for (ItemStack stack : displaced) {
      inv.addItem(stack);
    }
  }
}
 
Example 7
Source File: TNTMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void handleInstantActivation(BlockPlaceEvent event) {
    if(this.properties.instantIgnite && event.getBlock().getType() == Material.TNT) {
        World world = event.getBlock().getWorld();
        TNTPrimed tnt = world.spawn(BlockUtils.base(event.getBlock()), TNTPrimed.class);

        if(this.properties.fuse != null) {
            tnt.setFuseTicks(this.getFuseTicks());
        }

        if(this.properties.power != null) {
            tnt.setYield(this.properties.power); // Note: not related to EntityExplodeEvent.yield
        }

        if(callPrimeEvent(tnt, event.getPlayer(), true)) {
            // Only cancel the block placement if the prime event is NOT cancelled.
            // If priming is cancelled, the block is allowed to stay (unless some
            // other handler has already cancelled the place event).
            event.setCancelled(true);
            world.playSound(tnt.getLocation(), Sound.ENTITY_TNT_PRIMED, 1, 1);

            ItemStack inHand = event.getItemInHand();
            if(inHand.getAmount() == 1) {
                inHand = null;
            } else {
                inHand.setAmount(inHand.getAmount() - 1);
            }
            event.getPlayer().getInventory().setItem(event.getHand(), inHand);
        }
    }
}
 
Example 8
Source File: KillRewardMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private void giveRewards(MatchPlayer killer, Collection<KillReward> rewards) {
  for (KillReward reward : rewards) {
    List<ItemStack> items = new ArrayList<>(reward.items);

    // Apply kit first so it can not override reward items
    reward.kit.apply(killer, false, items);

    for (ItemStack stack : items) {
      ItemStack clone = stack.clone();
      PlayerItemTransferEvent event =
          new PlayerItemTransferEvent(
              null,
              PlayerItemTransferEvent.Type.PLUGIN,
              killer.getBukkit(),
              null,
              null,
              killer.getBukkit().getInventory(),
              null,
              clone,
              null,
              clone.getAmount(),
              null);
      match.callEvent(event);
      if (!event.isCancelled() && event.getQuantity() > 0) {
        // BEWARE: addItem modifies its argument.. send in the clone!
        clone.setAmount(event.getQuantity());
        killer.getBukkit().getInventory().addItem(clone);
      }
    }
  }
}
 
Example 9
Source File: DuctListener.java    From Transport-Pipes with MIT License 5 votes vote down vote up
private void decreaseHandItem(Player p, EquipmentSlot hand) {
    if (p.getGameMode() == GameMode.CREATIVE) {
        return;
    }
    ItemStack item = hand == EquipmentSlot.HAND ? p.getInventory().getItemInMainHand() : p.getInventory().getItemInOffHand();
    if (item != null) {
        if (item.getAmount() <= 1) {
            item = null;
        } else {
            item.setAmount(item.getAmount() - 1);
        }
        if (hand == EquipmentSlot.HAND) p.getInventory().setItemInMainHand(item);
        else p.getInventory().setItemInOffHand(item);
    }
}
 
Example 10
Source File: GrindStone.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onInteract(Player p, Block b) {
	Block dispBlock = b.getRelative(BlockFace.DOWN);
	Dispenser disp = (Dispenser) dispBlock.getState();
	Inventory inv = disp.getInventory();
	
	for (ItemStack current : inv.getContents()) {
		for (ItemStack convert : RecipeType.getRecipeInputs(this)) {
			if (convert != null && SlimefunUtils.isItemSimilar(current, convert, true)) {
				ItemStack output = RecipeType.getRecipeOutput(this, convert);
				Inventory outputInv = findOutputInventory(output, dispBlock, inv);
				
				if (outputInv != null) {
					ItemStack removing = current.clone();
					removing.setAmount(1);
					inv.removeItem(removing);
					outputInv.addItem(output);
					p.getWorld().playSound(p.getLocation(), Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 1, 1);
				}
				else {
					SlimefunPlugin.getLocalization().sendMessage(p, "machines.full-inventory", true);
				}
				
				return;
			}
		}
	}
	SlimefunPlugin.getLocalization().sendMessage(p, "machines.unknown-material", true);
}
 
Example 11
Source File: MultiInventory.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public int addItem(ItemStack items) {
	// Try to find an open spot in any of the inventories.
	HashMap<Integer, ItemStack> leftovers;
	int leftoverAmount = 0;
	for (Inventory inv : invs) {
		
		// 1) Leftovers is the same size as items. This inv was full, move on to next.
		// 2) Leftovers is none or zero, we are done return
		// 3) keep trying to place the leftovers in another chest.
		
		leftoverAmount = 0;
		leftovers = inv.addItem(items);
		
		for (ItemStack i : leftovers.values()) {
			leftoverAmount += i.getAmount();
		}
		
		if (leftoverAmount == 0)
			return 0;
		
		if (leftoverAmount == items.getAmount())
			continue;
		
		// Some items were deposited, update the items count and try again.
		items.setAmount(leftoverAmount);
	
	}
	
	return leftoverAmount;
}
 
Example 12
Source File: ItemShortcut.java    From Minepacks with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Removes the backpack item form the drops on death
 */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onDeath(PlayerDeathEvent event)
{
	//region prevent drop
	Iterator<ItemStack> itemStackIterator = event.getDrops().iterator();
	while(itemStackIterator.hasNext())
	{
		if(isItemShortcut(itemStackIterator.next()))
		{
			itemStackIterator.remove();
			break;
		}
	}
	//endregion
	if(improveDeathChestCompatibility)
	{ // improveDeathChestCompatibility
		for(ItemStack itemStack : event.getEntity().getInventory())
		{
			if(isItemShortcut(itemStack))
			{
				itemStack.setAmount(0);
				itemStack.setType(Material.AIR);
			}
		}
	}
}
 
Example 13
Source File: ShopInteractListener.java    From ShopChest with MIT License 4 votes vote down vote up
/**
 * Removes items to from an inventory
 * @param inventory The inventory, from which the items will be removed
 * @param itemStack Items to remove
 * @return Whether all items were removed from the inventory
 */
private boolean removeFromInventory(Inventory inventory, ShopProduct product) {
    plugin.debug("Removing items from inventory...");

    HashMap<Integer, ItemStack> inventoryItems = new HashMap<>();
    ItemStack itemStack = product.getItemStack();
    int amount = product.getAmount();
    int removed = 0;

    if (inventory instanceof PlayerInventory) {
        if (Utils.getMajorVersion() >= 9) {
            inventoryItems.put(40, inventory.getItem(40));
        }

        for (int i = 0; i < 36; i++) {
            inventoryItems.put(i, inventory.getItem(i));
        }

    } else {
        for (int i = 0; i < inventory.getSize(); i++) {
            inventoryItems.put(i, inventory.getItem(i));
        }
    }

    slotLoop:
    for (int slot : inventoryItems.keySet()) {
        while (removed < amount) {
            ItemStack item = inventory.getItem(slot);

            if (item != null && item.getType() != Material.AIR) {
                if (Utils.isItemSimilar(item, itemStack)) {
                    if (item.getAmount() > 0) {
                        int newAmount = item.getAmount() - 1;

                        ItemStack newItemStack = new ItemStack(item);
                        newItemStack.setAmount(newAmount);

                        if (newAmount == 0)
                            inventory.setItem(slot, null);
                        else
                            inventory.setItem(slot, newItemStack);

                        removed++;
                    } else {
                        continue slotLoop;
                    }
                } else {
                    continue slotLoop;
                }
            } else {
                continue slotLoop;
            }

        }
    }

    return (removed == amount);
}
 
Example 14
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onInventoryClick(InventoryClickEvent event, final Player player) {
	super.onInventoryClick(event, player);
	final PlayerShopkeeper shopkeeper = this.getShopkeeper();
	int slot = event.getRawSlot();
	if (slot == 2 || slot == 6) {
		ItemStack[] inventory = player.getInventory().getContents();
		ItemStack hireCost = shopkeeper.getHireCost().clone();
		for (int i = 0; i < inventory.length; i++) {
			ItemStack item = inventory[i];
			if (item != null && item.isSimilar(hireCost)) {
				if (item.getAmount() > hireCost.getAmount()) {
					item.setAmount(item.getAmount() - hireCost.getAmount());
					hireCost.setAmount(0);
					break;
				} else if (item.getAmount() == hireCost.getAmount()) {
					inventory[i] = null;
					hireCost.setAmount(0);
					break;
				} else {
					hireCost.setAmount(hireCost.getAmount() - item.getAmount());
					inventory[i] = null;
				}
			}
		}

		if (hireCost.getAmount() == 0) {
			int maxShops = ShopkeepersPlugin.getInstance().getMaxShops(player);

			// call event:
			PlayerShopkeeperHiredEvent hireEvent = new PlayerShopkeeperHiredEvent(player, shopkeeper, maxShops);
			Bukkit.getPluginManager().callEvent(hireEvent);
			if (hireEvent.isCancelled()) {
				// close window for this player:
				this.closeDelayed(player);
				return;
			}

			// check max shops limit:
			maxShops = hireEvent.getMaxShopsForPlayer();
			if (maxShops > 0) {
				int count = ShopkeepersPlugin.getInstance().countShopsOfPlayer(player);
				if (count >= maxShops) {
					Utils.sendMessage(player, Settings.msgTooManyShops);
					this.closeDelayed(player);
					return;
				}
			}

			// hire it:
			player.getInventory().setContents(inventory); // apply inventory changes
			shopkeeper.setForHire(false, null);
			shopkeeper.setOwner(player);
			ShopkeepersPlugin.getInstance().save();
			Utils.sendMessage(player, Settings.msgHired);

			// close all open windows for this shopkeeper:
			shopkeeper.closeAllOpenWindows();
			return;
		} else {
			// not enough money:
			Utils.sendMessage(player, Settings.msgCantHire);
			// close window for this player:
			this.closeDelayed(player);
		}
	}
}
 
Example 15
Source File: PlayerInventoryImpl.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@Override
public HashMap<Integer, ItemStack> addItem(ItemStack... items) {
    Validate.noNullElements(items, "Item cannot be null");
    HashMap<Integer, ItemStack> leftover = new HashMap();

    label35:
    for(int i = 0; i < items.length; ++i) {
        ItemStack item = items[i];

        while(true) {
            while(true) {
                int firstPartial = this.firstPartial(item);
                if (firstPartial == -1) {
                    int firstFree = this.firstEmpty();
                    if (firstFree == -1) {
                        leftover.put(i, item);
                        continue label35;
                    }

                    if (item.getAmount() <= 64) {
                        this.setItem(firstFree, item);
                        continue label35;
                    }

                    ItemStack stack = item.clone();
                    stack.setAmount(64);
                    this.setItem(firstFree, stack);
                    item.setAmount(item.getAmount() - 64);
                } else {
                    ItemStack partialItem = this.getItem(firstPartial);
                    int amount = item.getAmount();
                    int partialAmount = partialItem.getAmount();
                    int maxAmount = partialItem.getMaxStackSize();
                    if (amount + partialAmount <= maxAmount) {
                        partialItem.setAmount(amount + partialAmount);
                        this.setItem(firstPartial, partialItem);
                        continue label35;
                    }

                    partialItem.setAmount(maxAmount);
                    this.setItem(firstPartial, partialItem);
                    item.setAmount(amount + partialAmount - maxAmount);
                }
            }
        }
    }

    return leftover;
}
 
Example 16
Source File: CargoUtils.java    From Slimefun4 with GNU General Public License v3.0 4 votes vote down vote up
static ItemStack insert(Block node, Block target, ItemStack stack) {
    if (!matchesFilter(node, stack)) {
        return stack;
    }

    DirtyChestMenu menu = getChestMenu(target);

    if (menu == null) {
        if (hasInventory(target)) {
            BlockState state = target.getState();

            if (state instanceof InventoryHolder) {
                return insertIntoVanillaInventory(stack, ((InventoryHolder) state).getInventory());
            }
        }

        return stack;
    }

    ItemStackWrapper wrapper = new ItemStackWrapper(stack);

    for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.INSERT, stack)) {
        ItemStack itemInSlot = menu.getItemInSlot(slot);
        if (itemInSlot == null) {
            menu.replaceExistingItem(slot, stack);
            return null;
        }

        int maxStackSize = itemInSlot.getType().getMaxStackSize();
        int currentAmount = itemInSlot.getAmount();

        if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && currentAmount < maxStackSize) {
            int amount = currentAmount + stack.getAmount();

            itemInSlot.setAmount(Math.min(amount, maxStackSize));
            if (amount > maxStackSize) {
                stack.setAmount(amount - maxStackSize);
            }
            else {
                stack = null;
            }

            menu.replaceExistingItem(slot, itemInSlot);
            return stack;
        }
    }

    return stack;
}
 
Example 17
Source File: QuickShopItemMatcherImpl.java    From QuickShop-Reremake with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Compares two items to each other. Returns true if they match. Rewrite it to use more faster
 * hashCode.
 *
 * @param requireStack The first item stack
 * @param givenStack   The second item stack
 * @return true if the itemstacks match. (Material, durability, enchants, name)
 */
public boolean matches(@Nullable ItemStack requireStack, @Nullable ItemStack givenStack) {
    if (requireStack == null && givenStack == null) {
        return true;
    }

    if (requireStack == null || givenStack == null) {
        Util.debugLog(
                "Match failed: A stack is null: "
                        + "requireStack["
                        + requireStack
                        + "] givenStack["
                        + givenStack
                        + "]");
        return false; // One of them is null (Can't be both, see above)
    }

    requireStack = requireStack.clone();
    requireStack.setAmount(1);
    givenStack = givenStack.clone();
    givenStack.setAmount(1);

    if (workType == 1) {
        return requireStack.isSimilar(givenStack);
    }
    if (workType == 2) {
        return requireStack.equals(givenStack);
    }

    if (!typeMatches(requireStack, givenStack)) {
        return false;
    }

    if (requireStack.hasItemMeta() != givenStack.hasItemMeta()) {
        return false;
    }
    if (requireStack.hasItemMeta()) {
        return itemMetaMatcher.matches(requireStack, givenStack);
    }

    return true;
}
 
Example 18
Source File: AnvilListener.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
	HumanEntity he = event.getWhoClicked();

	if (!(he instanceof Player && event.getClickedInventory() instanceof AnvilInventory)) {
		return;
	}

	AnvilInventory inv = (AnvilInventory) event.getClickedInventory();
	Player player = (Player) he;

	ItemStack tool = inv.getItem(0);
	ItemStack modifier = inv.getItem(1);
	ItemStack newTool = inv.getItem(2);

	if (tool == null || modifier == null || newTool == null) {
		return;
	}

	if (event.getSlot() != 2) {
		return;
	}

	if (Lists.WORLDS.contains(player.getWorld().getName())) {
		return;
	}

	if (!(modManager.isToolViable(tool) || modManager.isArmorViable(tool))) {
		return;
	}

	//boolean deleteAllItems = false;
	if (event.getCursor() != null && !event.getCursor().getType().equals(Material.AIR)) {
		return;
	}

	if (!modManager.isModifierItem(modifier)) { //upgrade
		if (tool.getType().equals(newTool.getType())) return; //Not an upgrade

		if (new Random().nextInt(100) < MineTinker.getPlugin().getConfig().getInt("ChanceToFailToolUpgrade")) {
			newTool = tool;
			Bukkit.getPluginManager().callEvent(new ToolUpgradeEvent(player, newTool, false));
		} else {
			Bukkit.getPluginManager().callEvent(new ToolUpgradeEvent(player, newTool, true));
		}

		// ------ upgrade
		if (event.isShiftClick()) {
			if (player.getInventory().addItem(newTool).size() != 0) { //adds items to (full) inventory and then case if inventory is full
				event.setCancelled(true); //cancels the event if the player has a full inventory
				return;
			} // no else as it gets added in if-clause

			inv.clear();
			return;
		}

		player.setItemOnCursor(newTool);
		inv.clear();
	} else { //is modifier
		Modifier mod = modManager.getModifierFromItem(modifier);

		if (mod == null) {
			return;
		}

		modifier.setAmount(modifier.getAmount() - 1);

		if (new Random().nextInt(100) < MineTinker.getPlugin().getConfig().getInt("ChanceToFailModifierApply")) {
			newTool = tool;
			Bukkit.getPluginManager().callEvent(new ModifierFailEvent(player, tool, mod, ModifierFailCause.PLAYER_FAILURE, false));
		} else {
			Bukkit.getPluginManager().callEvent(new ModifierApplyEvent(player, tool, mod, modManager.getFreeSlots(newTool), false));
		}

		if (event.isShiftClick()) {
			if (player.getInventory().addItem(newTool).size() != 0) { //adds items to (full) inventory and then case if inventory is full
				event.setCancelled(true); //cancels the event if the player has a full inventory
				return;
			} // no else as it gets added in if-clause

			inv.clear();
			inv.setItem(1, modifier);

			return;
		}

		player.setItemOnCursor(newTool);

		inv.clear();
		inv.setItem(1, modifier);
	}
}
 
Example 19
Source File: CraftInventory.java    From Kettle with GNU General Public License v3.0 4 votes vote down vote up
public HashMap<Integer, ItemStack> addItem(ItemStack... items) {
    Validate.noNullElements(items, "Item cannot be null");
    HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();

    /* TODO: some optimization
     *  - Create a 'firstPartial' with a 'fromIndex'
     *  - Record the lastPartial per Material
     *  - Cache firstEmpty result
     */

    for (int i = 0; i < items.length; i++) {
        ItemStack item = items[i];
        while (true) {
            // Do we already have a stack of it?
            int firstPartial = firstPartial(item);

            // Drat! no partial stack
            if (firstPartial == -1) {
                // Find a free spot!
                int firstFree = firstEmpty();

                if (firstFree == -1) {
                    // No space at all!
                    leftover.put(i, item);
                    break;
                } else {
                    // More than a single stack!
                    if (item.getAmount() > getMaxItemStack()) {
                        CraftItemStack stack = CraftItemStack.asCraftCopy(item);
                        stack.setAmount(getMaxItemStack());
                        setItem(firstFree, stack);
                        item.setAmount(item.getAmount() - getMaxItemStack());
                    } else {
                        // Just store it
                        setItem(firstFree, item);
                        break;
                    }
                }
            } else {
                // So, apparently it might only partially fit, well lets do just that
                ItemStack partialItem = getItem(firstPartial);

                int amount = item.getAmount();
                int partialAmount = partialItem.getAmount();
                int maxAmount = partialItem.getMaxStackSize();

                // Check if it fully fits
                if (amount + partialAmount <= maxAmount) {
                    partialItem.setAmount(amount + partialAmount);
                    // To make sure the packet is sent to the client
                    setItem(firstPartial, partialItem);
                    break;
                }

                // It fits partially
                partialItem.setAmount(maxAmount);
                // To make sure the packet is sent to the client
                setItem(firstPartial, partialItem);
                item.setAmount(amount + partialAmount - maxAmount);
            }
        }
    }
    return leftover;
}
 
Example 20
Source File: Utils.java    From Shopkeepers with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Removes the specified amount of items which match the specified attributes from the given inventory.
 * 
 * @param inv
 * @param type
 *            The item type.
 * @param data
 *            The data value/durability. If -1 is is ignored.
 * @param displayName
 *            The displayName. If null it is ignored.
 * @param lore
 *            The item lore. If null or empty it is ignored.
 * @param ignoreNameAndLore
 * @param amount
 */
public static void removeItemsFromInventory(Inventory inv, Material type, short data, String displayName, List<String> lore, int amount) {
	for (ItemStack is : inv.getContents()) {
		if (!Utils.isSimilar(is, type, data, displayName, lore)) continue;
		int newamount = is.getAmount() - amount;
		if (newamount > 0) {
			is.setAmount(newamount);
			break;
		} else {
			inv.remove(is);
			amount = -newamount;
			if (amount == 0) break;
		}
	}
}