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

The following examples show how to use org.bukkit.inventory.ItemStack#isSimilar() . 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: InventoryImpl.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private int firstPartial(ItemStack item) {
    ItemStack[] inventory = this.getStorageContents();
    ItemStack filteredItem = item.clone();
    if (item == null) {
        return -1;
    } else {
        for(int i = 0; i < inventory.length; ++i) {
            ItemStack cItem = inventory[i];
            if (cItem != null && cItem.getAmount() < cItem.getMaxStackSize() && cItem.isSimilar(filteredItem)) {
                return i;
            }
        }

        return -1;
    }
}
 
Example 2
Source File: BlockContainer.java    From Transport-Pipes with MIT License 6 votes vote down vote up
/**
 * puts "put" into "before" and returns the result. if "put" can't be accumulated with "before", "before" is returned.
 * if "put" does not fit completely in "before", "put"'s amount decreases by how much does fit and the returned item will have an amount of the max stack size
 */
protected ItemStack accumulateItems(ItemStack before, ItemStack put) {
    if (put == null) {
        return before;
    }
    if (before == null) {
        ItemStack putCopy = put.clone();
        put.setAmount(0);
        return putCopy;
    }
    if (!before.isSimilar(put)) {
        return before;
    }
    int beforeAmount = before.getAmount();
    int putAmount = put.getAmount();
    int maxStackSize = before.getMaxStackSize();
    ItemStack returnItem = before.clone();
    returnItem.setAmount(Math.min(beforeAmount + putAmount, maxStackSize));
    put.setAmount(Math.max(putAmount - (maxStackSize - beforeAmount), 0));
    return returnItem;
}
 
Example 3
Source File: CraftItemStack.java    From Thermos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isSimilar(ItemStack stack) {
    if (stack == null) {
        return false;
    }
    if (stack == this) {
        return true;
    }
    if (!(stack instanceof CraftItemStack)) {
        return stack.getClass() == ItemStack.class && stack.isSimilar(this);
    }

    CraftItemStack that = (CraftItemStack) stack;
    if (handle == that.handle) {
        return true;
    }
    if (handle == null || that.handle == null) {
        return false;
    }
    if (!(that.getTypeId() == getTypeId() && getDurability() == that.getDurability())) {
        return false;
    }
    return hasItemMeta() ? that.hasItemMeta() && handle.stackTagCompound.equals(that.handle.stackTagCompound) : !that.hasItemMeta();
}
 
Example 4
Source File: Trade.java    From TradePlus with GNU General Public License v3.0 6 votes vote down vote up
private static List<ItemStack> combine(ItemStack[] items) {
  List<ItemStack> result = new ArrayList<>();
  for (int i = 0; i < items.length; i++) {
    ItemStack item = items[i];
    if (item == null) continue;
    item = item.clone();
    for (int j = i + 1; j < items.length; j++) {
      ItemStack dupe = items[j];
      if (item.isSimilar(dupe)) {
        item.setAmount(item.getAmount() + dupe.getAmount());
        items[j] = null;
      }
    }
    result.add(item);
  }
  return result;
}
 
Example 5
Source File: InventoryCompressor.java    From Minepacks with GNU General Public License v3.0 6 votes vote down vote up
private void move(ItemStack stack, int start)
{ // Search items that are the same
	int differentMetaStart = -1;
	for(int i = start; i < inputStacks.length; i++)
	{
		ItemStack stack2 = inputStacks[i];
		if(stack2 == null || stack2.getType() == Material.AIR || stack2.getAmount() < 1) continue;
		if(stack.isSimilar(stack2))
		{
			add(stack2); // Add item to sorted array
			inputStacks[i] = null; // Remove item from input
		}
		else if(differentMetaStart == -1 && stack.getType() == stack2.getType())
		{ // Same material but different meta
			differentMetaStart = i;
		}
	}
	if(differentMetaStart >= 0)
		move(inputStacks[differentMetaStart], differentMetaStart);
}
 
Example 6
Source File: ItemUtils.java    From AdditionsAPI with MIT License 5 votes vote down vote up
/**
 * get the slot index of the first occurrence of the given item in given
 * inventory.<br>
 * returns -1 if not found. <br>
 * Note: does not compare amount. <br>
 */
public static int getSlot(Inventory inv, ItemStack item) {

	for (int i = 0; i < inv.getSize(); i++) {
		ItemStack temp = inv.getItem(i);
		if (temp != null && temp.isSimilar(item)) {
			return i;
		}
	}

	return -1;
}
 
Example 7
Source File: PlayerItemTransferEvent.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Return the quantity of items stackable with the given item that
 * the player was in posession of prior to the transfer event. This
 * includes any items being carried on the cursor.
 */
public int getPriorQuantity(ItemStack type) {
    int quantity = 0;
    for(ItemStack stack : this.player.getInventory().contents()) {
        if(stack != null && stack.isSimilar(type)) {
            quantity += stack.getAmount();
        }
    }
    if(this.cursorItems != null && this.cursorItems.isSimilar(type)) {
        quantity += this.cursorItems.getAmount();
    }
    return quantity;
}
 
Example 8
Source File: GunRefillerRunnable.java    From QualityArmory with GNU General Public License v3.0 5 votes vote down vote up
public static boolean hasItemReloaded(Player reloader, ItemStack is) {
	for (GunRefillerRunnable s : allGunRefillers) {
		if (is.isSimilar(s.reloadedItem))
			if(reloader == null || reloader == s.reloader);
			return true;
	}
	return false;
}
 
Example 9
Source File: InventoryGui.java    From InventoryGui with MIT License 5 votes vote down vote up
/**
 * Add items to a stack up to the max stack size
 * @param item  The base item
 * @param add   The item stack to add
 * @return <tt>true</tt> if the stack is finished; <tt>false</tt> if these stacks can't be merged
 */
private static boolean addToStack(ItemStack item, ItemStack add) {
    if (item.isSimilar(add)) {
        int newAmount = item.getAmount() + add.getAmount();
        if (newAmount >= item.getMaxStackSize()) {
            item.setAmount(item.getMaxStackSize());
            add.setAmount(newAmount - item.getAmount());
        } else {
            item.setAmount(newAmount);
            add.setAmount(0);
        }
        return true;
    }
    return false;
}
 
Example 10
Source File: CraftInventory.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public boolean containsAtLeast(ItemStack item, int amount) {
    if (item == null) {
        return false;
    }
    if (amount <= 0) {
        return true;
    }
    for (ItemStack i : getContents()) {
        if (item.isSimilar(i) && (amount -= i.getAmount()) <= 0) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: InventoryTaskType.java    From Quests with MIT License 5 votes vote down vote up
private int getAmount(Player player, ItemStack is, int max) {
    if (is == null) {
        return 0;
    }
    int amount = 0;
    for (int i = 0; i < 36; i++) {
        ItemStack slot = player.getInventory().getItem(i);
        if (slot == null || !slot.isSimilar(is))
            continue;
        amount += slot.getAmount();
    }
    return Math.min(amount, max);
}
 
Example 12
Source File: CraftInventory.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
private int firstPartial(ItemStack item) {
    ItemStack[] inventory = getStorageContents();
    ItemStack filteredItem = CraftItemStack.asCraftCopy(item);
    if (item == null) {
        return -1;
    }
    for (int i = 0; i < inventory.length; i++) {
        ItemStack cItem = inventory[i];
        if (cItem != null && cItem.getAmount() < cItem.getMaxStackSize() && cItem.isSimilar(filteredItem)) {
            return i;
        }
    }
    return -1;
}
 
Example 13
Source File: RecipeShapeless.java    From ProRecipes with GNU General Public License v2.0 5 votes vote down vote up
public boolean matchLowest(RecipeShapeless recipe){
	if(!match(recipe)){
		
		ArrayList<ItemStack> tt = new ArrayList<ItemStack>();
		tt.addAll(recipe.items);
		
		boolean contains = false;
		for(ItemStack i : items){
			contains = false;
			ItemStack latest = new ItemStack(Material.AIR);
			
			for(ItemStack p : tt){
				ItemStack out = i.clone();
				ItemStack in = p.clone();
				out.setAmount(1);
				in.setAmount(1);
				
				if(in.isSimilar(out)){
					if(i.getAmount() <= p.getAmount()){
						contains = true;
						latest = p;
						break;
					}else{
						contains = false;
						return false;
					}
				}
			}
			tt.remove(latest);
			
			if(!contains){
				return false;
			}
		}
		return contains;
	}else{
		return true;
	}
}
 
Example 14
Source File: PlayerInventoryImpl.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private int first(ItemStack item, boolean withAmount) {
    if (item == null) {
        return -1;
    } else {
        ItemStack[] inventory = this.getStorageContents();
        int i = 0;

        while(true) {
            if (i >= inventory.length) {
                return -1;
            }

            if (inventory[i] != null) {
                if (withAmount) {
                    if (item.equals(inventory[i])) {
                        break;
                    }
                } else if (item.isSimilar(inventory[i])) {
                    break;
                }
            }

            ++i;
        }

        return i;
    }
}
 
Example 15
Source File: Slot.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public int maxTransferrableIn(ItemStack source, I inv) {
    final ItemStack dest = getItem(inv);
    if(ItemUtils.isNothing(dest)) {
        return maxTransferrableIn(source);
    } else if(dest.isSimilar(source)) {
        return Math.min(source.getAmount(), Math.max(0, maxStackSize(dest) - dest.getAmount()));
    } else {
        return 0;
    }
}
 
Example 16
Source File: ItemUtils.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
public static int getItemAmount(ItemStack item, Inventory inv) {
    int amount = 0;

    for (ItemStack is : inv.getContents()) {
        if (item.isSimilar(is)) {
            amount += is.getAmount();
        }
    }

    return amount;
}
 
Example 17
Source File: InventoryUtils.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ItemStack placeStack(Inventory inv, int slot, ItemStack stack) {
  ItemStack placed = inv.getItem(slot);
  int max = Math.min(inv.getMaxStackSize(), stack.getMaxStackSize());
  int amount;
  int leftover;

  if (isNothing(placed)) {
    amount = Math.min(max, stack.getAmount());
    leftover = Math.max(0, stack.getAmount() - amount);
  } else if (placed.isSimilar(stack)) {
    amount = Math.min(max, placed.getAmount() + stack.getAmount());
    leftover = placed.getAmount() + stack.getAmount() - amount;
  } else {
    return stack;
  }

  if (leftover == stack.getAmount()) {
    return stack;
  } else {
    placed = stack.clone();
    placed.setAmount(amount);
    inv.setItem(slot, placed);

    stack = stack.clone();
    stack.setAmount(leftover);
    return stack;
  }
}
 
Example 18
Source File: ShopInventory.java    From BedWars with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void handleBuy(ShopTransactionEvent event) {
	Player player = event.getPlayer();
	Game game = Main.getPlayerGameProfile(event.getPlayer()).getGame();
	ClickType clickType = event.getClickType();
	MapReader mapReader = event.getItem().getReader();
	String priceType = event.getType().toLowerCase();
	ItemSpawnerType type = Main.getSpawnerType(priceType);
	ItemStack newItem = event.getStack();

	int amount = newItem.getAmount();
	int price = event.getPrice();
	int inInventory = 0;

	if (mapReader.containsKey("currency-changer")) {
		String changeItemToName = mapReader.getString("currency-changer");
		ItemSpawnerType changeItemType;
		if (changeItemToName == null) {
			return;
		}

		changeItemType = Main.getSpawnerType(changeItemToName);
		if (changeItemType == null) {
			return;
		}

		newItem = changeItemType.getStack();
	}

	if (clickType.isShiftClick()) {
		double priceOfOne = (double) price / amount;
		double maxStackSize;
		int finalStackSize;

		for (ItemStack itemStack : event.getPlayer().getInventory().getStorageContents()) {
			if (itemStack != null && itemStack.isSimilar(type.getStack())) {
				inInventory = inInventory + itemStack.getAmount();
			}
		}
		if (Main.getConfigurator().config.getBoolean("sell-max-64-per-click-in-shop")) {
			maxStackSize = Math.min(inInventory / priceOfOne, 64);
		} else {
			maxStackSize = inInventory / priceOfOne;
		}

		finalStackSize = (int) maxStackSize;
		if (finalStackSize > amount) {
			price = (int) (priceOfOne * finalStackSize);
			newItem.setAmount(finalStackSize);
			amount = finalStackSize;
		}
	}

	ItemStack materialItem = type.getStack(price);
	if (event.hasPlayerInInventory(materialItem)) {
		if (event.hasProperties()) {
			for (ItemProperty property : event.getProperties()) {
				if (property.hasName()) {
					BedwarsApplyPropertyToBoughtItem applyEvent = new BedwarsApplyPropertyToBoughtItem(game, player,
						newItem, property.getReader(player).convertToMap());
					Main.getInstance().getServer().getPluginManager().callEvent(applyEvent);

					newItem = applyEvent.getStack();
				}
			}
		}

		event.sellStack(materialItem);
		event.buyStack(newItem);

		if (!Main.getConfigurator().config.getBoolean("removePurchaseMessages", false)) {
			player.sendMessage(i18n("buy_succes").replace("%item%", amount + "x " + getNameOrCustomNameOfItem(newItem))
					.replace("%material%", price + " " + type.getItemName()));
		}
		Sounds.playSound(player, player.getLocation(),
			Main.getConfigurator().config.getString("sounds.on_item_buy"), Sounds.ENTITY_ITEM_PICKUP, 1, 1);
	} else {
		if (!Main.getConfigurator().config.getBoolean("removePurchaseMessages", false)) {
			player.sendMessage(i18n("buy_failed").replace("%item%", amount + "x " + getNameOrCustomNameOfItem(newItem))
					.replace("%material%", price + " " + type.getItemName()));
		}
	}
}
 
Example 19
Source File: ItemsCraftedListener.java    From Statz with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get the amount of items the player had just crafted.
 * This method will take into consideration shift clicking &
 * the amount of inventory space the player has left.
 *
 * @param e CraftItemEvent
 * @return int: actual crafted item amount
 * @author lewysryan (https://www.spigotmc
 * .org/threads/util-get-the-crafted-item-amount-from-a-craftitemevent.162952/)
 */
private int getCraftAmount(CraftItemEvent e) {

    if (e.isCancelled()) {
        return 0;
    }

    Player p = (Player) e.getWhoClicked();

    if (e.isShiftClick()) {
        int itemsChecked = 0;
        int possibleCreations = 1;

        int amountCanBeMade = 0;

        for (ItemStack item : e.getInventory().getMatrix()) {
            if (item != null && item.getType() != Material.AIR) {
                if (itemsChecked == 0) {
                    possibleCreations = item.getAmount();
                    itemsChecked++;
                } else {
                    possibleCreations = Math.min(possibleCreations, item.getAmount());
                }
            }
        }

        int amountOfItems = e.getRecipe().getResult().getAmount() * possibleCreations;

        ItemStack i = e.getRecipe().getResult();

        for (int s = 0; s <= e.getInventory().getSize(); s++) {
            ItemStack test = p.getInventory().getItem(s);
            if (test == null || test.getType() == Material.AIR) {
                amountCanBeMade += i.getMaxStackSize();
                continue;
            }
            if (test.isSimilar(i)) {
                amountCanBeMade += i.getMaxStackSize() - test.getAmount();
            }
        }

        return amountOfItems > amountCanBeMade ? amountCanBeMade : amountOfItems;
    } else {
        return e.getRecipe().getResult().getAmount();
    }
}
 
Example 20
Source File: DefaultDropsHandler.java    From EliteMobs with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
    public void onDeath(EntityDeathEvent event) {

        if (!EntityTracker.isEliteMob(event.getEntity())) return;

        if (!EntityTracker.isNaturalEntity(event.getEntity()) &&
                !ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.SPAWNER_DEFAULT_LOOT_MULTIPLIER))
            return;

        List<ItemStack> droppedItems = event.getDrops();
        int mobLevel = (int) (EntityTracker.getEliteMobEntity(event.getEntity()).getLevel() *
                ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.DEFAULT_LOOT_MULTIPLIER));

        if (mobLevel > ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER))
            mobLevel = ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER);

        inventoryItemsConstructor(event.getEntity());

        for (ItemStack itemStack : droppedItems) {

//                ItemStack can be null for some reason, probably due to other plugins
            if (itemStack == null) continue;
            boolean itemIsWorn = false;

            for (ItemStack wornItem : wornItems)
                if (wornItem.isSimilar(itemStack))
                    itemIsWorn = true;

            if (!itemIsWorn)
                for (int i = 0; i < mobLevel * 0.1; i++)
                    event.getEntity().getLocation().getWorld().dropItem(event.getEntity().getLocation(), itemStack);

        }

        mobLevel = (int) (EntityTracker.getEliteMobEntity(event.getEntity()).getLevel() *
                ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.EXPERIENCE_LOOT_MULTIPLIER));

        int droppedXP = (int) (event.getDroppedExp() + event.getDroppedExp() * 0.1 * mobLevel);
        event.setDroppedExp(0);
        event.getEntity().getWorld().spawn(event.getEntity().getLocation(), ExperienceOrb.class).setExperience(droppedXP);

    }