Java Code Examples for org.bukkit.inventory.ItemStack#getAmount()
The following examples show how to use
org.bukkit.inventory.ItemStack#getAmount() .
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: BlueprintsMenu.java From Civs with GNU General Public License v3.0 | 6 votes |
private void addItemFromItemsInView(HashMap<String, Integer> itemsInView, String name, ItemStack is, Map<String, Integer> stashItems) { if (itemsInView.get(name) >= is.getAmount()) { itemsInView.put(name, itemsInView.get(name) - is.getAmount()); } else { if (itemsInView.get(name) < is.getAmount()) { int amount = is.getAmount() - itemsInView.get(name); if (stashItems.containsKey(name)) { stashItems.put(name, amount + stashItems.get(name)); } else { stashItems.put(name, amount); } } itemsInView.remove(name); } }
Example 2
Source File: BlockContainer.java From Transport-Pipes with MIT License | 6 votes |
/** * 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: CrazyCrates.java From Crazy-Crates with MIT License | 6 votes |
/** * Get the amount of physical keys a player has. */ public int getPhysicalKeys(Player player, Crate crate) { int keys = 0; for (ItemStack item : player.getOpenInventory().getBottomInventory().getContents()) { if (item != null) { if (Methods.isSimilar(item, crate)) { keys += item.getAmount(); } else { NBTItem nbtItem = new NBTItem(item); if (nbtItem.hasKey("CrazyCrates-Crate")) { if (crate.getName().equals(nbtItem.getString("CrazyCrates-Crate"))) { keys += item.getAmount(); } } } } } return keys; }
Example 4
Source File: FurnaceContainer.java From Transport-Pipes with MIT License | 6 votes |
@Override public ItemStack extractItem(TPDirection extractDirection, int amount, ItemFilter itemFilter) { if (!isInLoadedChunk()) { return null; } if (isInvLocked(cachedFurnace)) { return null; } if (itemFilter.applyFilter(cachedInv.getResult()) > 0) { ItemStack resultItem = cachedInv.getResult().clone(); ItemStack returnItem = resultItem.clone(); int resultItemAmount = resultItem.getAmount(); resultItem.setAmount(Math.max(resultItemAmount - amount, 0)); cachedInv.setResult(resultItem.getAmount() >= 1 ? resultItem : null); returnItem.setAmount(Math.min(amount, resultItemAmount)); return returnItem; } return null; }
Example 5
Source File: CVInventory.java From Civs with GNU General Public License v3.0 | 6 votes |
private boolean adjustItemToAdd(ArrayList<ItemStack> itemStacks, Map<Integer, ItemStack> contentsToModify, int i) { boolean itemAdded = false; ItemStack currentStack = itemStacks.get(0); if (!contentsToModify.containsKey(i)) { contentsToModify.put(i, currentStack); itemStacks.remove(0); itemAdded = true; } else if (contentsToModify.get(i).isSimilar(currentStack)) { if (contentsToModify.get(i).getAmount() + currentStack.getAmount() < currentStack.getMaxStackSize()) { contentsToModify.get(i).setAmount(contentsToModify.get(i).getAmount() + currentStack.getAmount()); itemStacks.remove(0); itemAdded = true; } else if (contentsToModify.get(i).getMaxStackSize() < contentsToModify.get(i).getAmount() + currentStack.getAmount()) { int difference = currentStack.getMaxStackSize() - contentsToModify.get(i).getAmount(); contentsToModify.get(i).setAmount(currentStack.getMaxStackSize()); currentStack.setAmount(currentStack.getAmount() - difference); } } return itemAdded; }
Example 6
Source File: ThrowableFireballListener.java From BedWars with GNU Lesser General Public License v3.0 | 5 votes |
@EventHandler public void onFireballThrow(PlayerInteractEvent event) { Player player = event.getPlayer(); if (!Main.isPlayerInGame(player)) { return; } if (event.getItem() != null) { ItemStack stack = event.getItem(); String unhash = APIUtils.unhashFromInvisibleStringStartsWith(stack, THROWABLE_FIREBALL_PREFIX); if (unhash != null && (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR)) { String[] properties = unhash.split(":"); double damage = Double.parseDouble(properties[2]); float explosion = (float) Double.parseDouble(properties[2]); Fireball fireball = player.launchProjectile(Fireball.class); fireball.setIsIncendiary(false); fireball.setYield(explosion); Main.registerGameEntity(fireball, Main.getPlayerGameProfile(player).getGame()); event.setCancelled(true); if (stack.getAmount() > 1) { stack.setAmount(stack.getAmount() - 1); } else { player.getInventory().remove(stack); } player.updateInventory(); } } }
Example 7
Source File: JsonItem.java From TrMenu with MIT License | 5 votes |
public static String toJson(ItemStack item) { JsonObject json = new JsonObject(); String type = item.getType().name(); byte data = item.getData().getData(); int amount = item.getAmount(); json.addProperty("type", item.getType().name()); if (data > 0) { json.addProperty("data", data); } if (amount > 1) { json.addProperty("amount", amount); } if (item.hasItemMeta()) { // Uncolor ItemMeta meta = item.getItemMeta(); if (meta.hasDisplayName()) { meta.setDisplayName(meta.getDisplayName().replace('§', '&')); } if (meta.hasLore()) { List<String> lore = meta.getLore(); lore.replaceAll(s -> s.replace('§', '&')); meta.setLore(lore); } item.setItemMeta(meta); json.add("meta", new JsonParser().parse(NMS.handle().loadNBT(item).toJson())); } return json.toString(); }
Example 8
Source File: PlayerInventoryImpl.java From Civs with GNU General Public License v3.0 | 5 votes |
@Override public HashMap<Integer, ItemStack> removeItem(ItemStack... items) throws IllegalArgumentException { Validate.notNull(items, "Items cannot be null"); HashMap<Integer, ItemStack> leftover = new HashMap(); for(int i = 0; i < items.length; ++i) { ItemStack item = items[i]; int toDelete = item.getAmount(); while(true) { int first = this.first(item, false); if (first == -1) { item.setAmount(toDelete); leftover.put(i, item); break; } ItemStack itemStack = this.getItem(first); int amount = itemStack.getAmount(); if (amount <= toDelete) { toDelete -= amount; this.clear(first); } else { itemStack.setAmount(amount - toDelete); this.setItem(first, itemStack); toDelete = 0; } if (toDelete <= 0) { break; } } } return leftover; }
Example 9
Source File: Resident.java From civcraft with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("deprecation") public boolean takeItem(int itemId, int itemData, int amount) throws CivException { Player player = CivGlobal.getPlayer(this); Inventory inv = player.getInventory(); if (!inv.contains(itemId)) { return false; } HashMap<Integer, ? extends ItemStack> stacks; stacks = inv.all(itemId); for (ItemStack stack : stacks.values()) { if (stack.getData().getData() != (byte)itemData) { continue; } if (stack.getAmount() <= 0) continue; if (stack.getAmount() < amount) { amount -= stack.getAmount(); stack.setAmount(0); inv.removeItem(stack); continue; } else { stack.setAmount(stack.getAmount()-amount); break; } } player.updateInventory(); return true; }
Example 10
Source File: CraftInventory.java From Thermos with GNU General Public License v3.0 | 5 votes |
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: Slot.java From PGM with GNU Affero General Public License v3.0 | 5 votes |
/** * Put the given stack in this slot of the given holder's inventory. * * @return a stack of any items that were NOT placed in the inventory, or null if the entire stack * was placed. This can only be non-null when placing in the auto-slot. */ public @Nullable ItemStack putItem(HumanEntity holder, ItemStack stack) { if (isAuto()) { stack = addItem(holder, stack); return stack.getAmount() > 0 ? stack : null; } else { getInventory(holder).setItem(getIndex(), stack); return null; } }
Example 12
Source File: Blacksmith.java From civcraft with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("deprecation") public void depositSmelt(Player player, ItemStack itemsInHand) throws CivException { // Make sure that the item is a valid smelt type. if (!Blacksmith.canSmelt(itemsInHand.getTypeId())) { throw new CivException ("Can only smelt gold and iron ore."); } // Only members can use the smelter Resident res = CivGlobal.getResident(player.getName()); if (!res.hasTown() || this.getTown() != res.getTown()) { throw new CivException ("Can only use the smelter if you are a town member."); } String value = convertType(itemsInHand.getTypeId())+":"+(itemsInHand.getAmount()*Blacksmith.YIELD_RATE); String key = getkey(player, this, "smelt"); // Store entry in session DB sessionAdd(key, value); // Take ore away from player. player.getInventory().removeItem(itemsInHand); //BukkitTools.sch // Schedule a message to notify the player when the smelting is finished. BukkitObjects.scheduleAsyncDelayedTask(new NotificationTask(player.getName(), CivColor.LightGreen+" Your stack of "+itemsInHand.getAmount()+" "+ CivData.getDisplayName(itemsInHand.getTypeId())+" has finished smelting."), TimeTools.toTicks(SMELT_TIME_SECONDS)); CivMessage.send(player,CivColor.LightGreen+ "Deposited "+itemsInHand.getAmount()+ " ore."); player.updateInventory(); }
Example 13
Source File: PlayerInventoryImpl.java From Civs with GNU General Public License v3.0 | 5 votes |
public int firstPartial(Material material) { Validate.notNull(material, "Material cannot be null"); ItemStack[] inventory = this.getStorageContents(); for(int i = 0; i < inventory.length; ++i) { ItemStack item = inventory[i]; if (item != null && item.getType() == material && item.getAmount() < item.getMaxStackSize()) { return i; } } return -1; }
Example 14
Source File: MultiInventory.java From civcraft with GNU General Public License v2.0 | 5 votes |
private int removeItemFromInventory(Inventory inv, String mid, int type, short data, int amount) { int removed = 0; int notRemoved = amount; ItemStack[] contents = inv.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack stack = contents[i]; if(!isCorrectItemStack(stack, mid, type, data)) { continue; } /* We've got the item we're looking for, lets remove as many as we can. */ int stackAmount = stack.getAmount(); if (stackAmount > notRemoved) { /* We've got more than enough in this stack. Reduce it's size. */ stack.setAmount(stackAmount - notRemoved); removed = notRemoved; notRemoved = 0; /* We've got it all. */ } else if (stackAmount == notRemoved) { /* Got the entire stack, null it out. */ contents[i] = null; removed = notRemoved; notRemoved = 0; } else { /* There was some in this stack, but not enough for all we were looking for. */ removed += stackAmount; notRemoved -= stackAmount; contents[i] = null; } if (notRemoved == 0) { /* We've removed everything. No need to continue. */ break; } } inv.setContents(contents); return removed; }
Example 15
Source File: ReportChestsTask.java From civcraft with GNU General Public License v2.0 | 5 votes |
private int countItem(Inventory inv, int id) { int total = 0; for (ItemStack stack : inv.all(ItemManager.getMaterial(id)).values()) { total += stack.getAmount(); } return total; }
Example 16
Source File: SoulboundRune.java From Slimefun4 with GNU General Public License v3.0 | 4 votes |
private void activate(Player p, PlayerDropItemEvent e, Item item) { // Being sure the entity is still valid and not picked up or whatsoever. if (!item.isValid()) { return; } Location l = item.getLocation(); Collection<Entity> entites = l.getWorld().getNearbyEntities(l, RANGE, RANGE, RANGE, this::findCompatibleItem); Optional<Entity> optional = entites.stream().findFirst(); if (optional.isPresent()) { Item entity = (Item) optional.get(); ItemStack target = entity.getItemStack(); SlimefunUtils.setSoulbound(target, true); if (target.getAmount() == 1) { e.setCancelled(true); // This lightning is just an effect, it deals no damage. l.getWorld().strikeLightningEffect(l); Slimefun.runSync(() -> { // Being sure entities are still valid and not picked up or whatsoever. if (item.isValid() && entity.isValid() && target.getAmount() == 1) { l.getWorld().createExplosion(l, 0); l.getWorld().playSound(l, Sound.ENTITY_GENERIC_EXPLODE, 0.3F, 1); entity.remove(); item.remove(); l.getWorld().dropItemNaturally(l, target); SlimefunPlugin.getLocalization().sendMessage(p, "messages.soulbound-rune.success", true); } }, 10L); } else { SlimefunPlugin.getLocalization().sendMessage(p, "messages.soulbound-rune.fail", true); } } }
Example 17
Source File: WandCondition.java From BetonQuest with GNU General Public License v3.0 | 4 votes |
@Override protected Boolean execute(String playerID) throws QuestRuntimeException { Player player = PlayerConverter.getPlayer(playerID); int heldAmount; switch (type) { case IS_LOST: for (LostWand lost : api.getLostWands()) { Player owner = Bukkit.getPlayer(UUID.fromString(lost.getOwnerId())); if (owner == null) continue; if (owner.equals(player)) { return true; } } return false; case IN_HAND: ItemStack wandItem = null; wandItem = player.getInventory().getItemInMainHand(); if (!api.isWand(wandItem)) { return false; } Wand wand1 = api.getWand(wandItem); return checkWand(wand1, playerID); case IN_INVENTORY: heldAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item == null) continue; if (api.isWand(item)) { Wand wand2 = api.getWand(item); if (checkWand(wand2, playerID)) { heldAmount += item.getAmount(); if (amount == null || heldAmount >= amount.getInt(playerID)) { return true; } } } } return false; default: return false; } }
Example 18
Source File: ResidentCommand.java From civcraft with GNU General Public License v2.0 | 4 votes |
public void exchange_cmd() throws CivException { Player player = getPlayer(); Resident resident = getResident(); String type = getNamedString(1, "Enter a type. E.g. iron, gold, diamond, emerald."); Integer amount = getNamedInteger(2); if (amount <= 0) { throw new CivException("You must exchange a positive, non-zero amount."); } type = type.toLowerCase(); int exchangeID; double rate; switch (type) { case "iron": exchangeID = CivData.IRON_INGOT; rate = CivSettings.iron_rate; break; case "gold": exchangeID = CivData.GOLD_INGOT; rate = CivSettings.gold_rate; break; case "diamond": exchangeID = CivData.DIAMOND; rate = CivSettings.diamond_rate; break; case "emerald": exchangeID = CivData.EMERALD; rate = CivSettings.emerald_rate; break; default: throw new CivException("Unknown exchange type "+type+" must be iron, gold, diamond, or emerald."); } double exchangeRate; try { exchangeRate = CivSettings.getDouble(CivSettings.civConfig, "global.exchange_rate"); } catch (InvalidConfiguration e) { e.printStackTrace(); throw new CivException("Internal configuration error!"); } ItemStack stack = ItemManager.createItemStack(exchangeID, 1); int total = 0; for (int i = 0; i < player.getInventory().getContents().length; i++) { ItemStack is = player.getInventory().getItem(i); if (is == null) { continue; } if (LoreCraftableMaterial.isCustom(is)) { continue; } if (ItemManager.getId(is) == exchangeID) { total += is.getAmount(); } } if (total == 0) { throw new CivException("You do not have any "+type); } if (amount > total) { amount = total; } stack.setAmount(amount); player.getInventory().removeItem(stack); double coins = amount*rate*exchangeRate; resident.getTreasury().deposit(coins); CivMessage.sendSuccess(player, "Exchanged "+amount+" "+type+" for "+coins+" coins."); }
Example 19
Source File: SignLogic.java From uSkyBlock with GNU General Public License v3.0 | 4 votes |
private void tryComplete(Player player, Location chestLoc, Challenge challenge) { BlockState state = chestLoc.getBlock().getState(); if (!(state instanceof Chest)) { return; } PlayerInfo playerInfo = plugin.getPlayerInfo(player); if (playerInfo == null || !playerInfo.getHasIsland()) { return; } ChallengeCompletion completion = challengeLogic.getChallenge(playerInfo, challenge.getName()); List<ItemStack> requiredItems = challenge.getRequiredItems(completion.getTimesCompletedInCooldown()); Chest chest = (Chest) state; int missing = 0; for (ItemStack required : requiredItems) { int diff = 0; if (!player.getInventory().containsAtLeast(required, required.getAmount())) { diff = required.getAmount() - plugin.getChallengeLogic().getCountOf(player.getInventory(), required); } if (diff > 0 && !chest.getInventory().containsAtLeast(required, diff)) { diff -= plugin.getChallengeLogic().getCountOf(chest.getInventory(), required); } else { diff = 0; } missing += diff; } if (missing == 0) { ItemStack[] items = requiredItems.toArray(new ItemStack[0]); ItemStack[] copy = ItemStackUtil.clone(requiredItems).toArray(new ItemStack[requiredItems.size()]); HashMap<Integer, ItemStack> missingItems = player.getInventory().removeItem(items); missingItems = chest.getInventory().removeItem(missingItems.values().toArray(new ItemStack[0])); if (!missingItems.isEmpty()) { // This effectively means, we just donated some items to the player (exploit!!) log.warning("Not all items removed from chest and player: " + missingItems.values()); } HashMap<Integer, ItemStack> leftOvers = player.getInventory().addItem(copy); if (leftOvers.isEmpty()) { plugin.getChallengeLogic().completeChallenge(player, challenge.getName()); } else { chest.getInventory().addItem(leftOvers.values().toArray(new ItemStack[0])); player.sendMessage(tr("\u00a7cWARNING:\u00a7e Could not transfer all the required items to your inventory!")); } updateSignsOnContainer(chest.getLocation()); } else { player.sendMessage(tr("\u00a7cNot enough items in chest to complete challenge!")); } }
Example 20
Source File: CargoUtils.java From Slimefun4 with GNU General Public License v3.0 | 4 votes |
static ItemStack insertIntoVanillaInventory(ItemStack stack, Inventory inv) { ItemStack[] contents = inv.getContents(); int minSlot = 0; int maxSlot = contents.length; // Check if it is a normal furnace if (inv instanceof FurnaceInventory) { // Check if it is fuel or not if (stack.getType().isFuel()) { maxSlot = 2; // Any non-smeltable items should not land in the upper slot if (!isSmeltable(stack, true)) { minSlot = 1; } } else { maxSlot = 1; } } else if (inv instanceof BrewerInventory) { if (stack.getType() == Material.POTION || stack.getType() == Material.LINGERING_POTION || stack.getType() == Material.SPLASH_POTION) { // Potions slot maxSlot = 3; } else if (stack.getType() == Material.BLAZE_POWDER) { // Blaze Powder slot minSlot = 4; maxSlot = 5; } else { // Input slot minSlot = 3; maxSlot = 4; } } ItemStackWrapper wrapper = new ItemStackWrapper(stack); for (int slot = minSlot; slot < maxSlot; slot++) { // Changes to this ItemStack are synchronized with the Item in the Inventory ItemStack itemInSlot = contents[slot]; if (itemInSlot == null) { inv.setItem(slot, stack); return null; } else { int maxStackSize = itemInSlot.getType().getMaxStackSize(); if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && itemInSlot.getAmount() < maxStackSize) { int amount = itemInSlot.getAmount() + stack.getAmount(); if (amount > maxStackSize) { stack.setAmount(amount - maxStackSize); } else { stack = null; } itemInSlot.setAmount(Math.min(amount, maxStackSize)); // Setting item in inventory will clone the ItemStack inv.setItem(slot, itemInSlot); return stack; } } } return stack; }