public static String InventoryToString(Inventory invInventory) { String serialization = invInventory.getSize() + ";"; for (int i = 0; i < invInventory.getSize(); i++) { ItemStack is = invInventory.getItem(i); if (is != null) { String serializedItemStack = new String(); String isType = String.valueOf(is.getType().getId()); serializedItemStack += "t@" + isType; if (is.getDurability() != 0) { String isDurability = String.valueOf(is.getDurability()); serializedItemStack += ":d@" + isDurability; } if (is.getAmount() != 1) { String isAmount = String.valueOf(is.getAmount()); serializedItemStack += ":a@" + isAmount; } Map<Enchantment, Integer> isEnch = is.getEnchantments(); if (isEnch.size() > 0) { for (Entry<Enchantment, Integer> ench : isEnch.entrySet()) { serializedItemStack += ":e@" + ench.getKey().getId() + "@" + ench.getValue(); } } serialization += i + "#" + serializedItemStack + ";"; } } return serialization; }
// Returns true if this item matches the item from a recipe public static boolean ingredientsMatch(ItemStack usedItem, ItemStack recipeItem) { if (!recipeItem.getType().equals(usedItem.getType())) { return false; } return recipeItem.getDurability() == -1 || recipeItem.getDurability() == usedItem.getDurability(); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityRightClick(PlayerInteractEntityEvent event) { QuestManager qm = Quester.qMan; Player player = event.getPlayer(); Quest quest = qm.getPlayerQuest(player.getName()); if (quest != null) { if (!quest.allowedWorld(player.getWorld().getName().toLowerCase())) return; List<Objective> objs = quest.getObjectives(); Entity entity = event.getRightClicked(); ItemStack item = player.getItemInHand(); for (int i = 0; i < objs.size(); i++) { if (objs.get(i).getType().equalsIgnoreCase("DYE")) { if (!qm.isObjectiveActive(player, i)) { continue; } DyeObjective obj = (DyeObjective) objs.get(i); if (entity.getType() == EntityType.SHEEP) { Sheep sheep = (Sheep) entity; if (item.getType() == Material.INK_SACK && obj.checkDye(15 - item.getDurability()) && sheep.getColor().getDyeData() != (15 - item.getDurability())) { qm.incProgress(player, i); return; } } } } } }
public static int countItemsInInventory(PlayerInventory inventory, ItemStack item) { int totalAmount = 0; boolean isDurable = Items.itemByStack(item).isDurable(); for (Integer i : inventory.all(item.getType()).keySet()) { ItemStack thisStack = inventory.getItem(i); if (!isDurable && thisStack.getDurability() != item.getDurability()) { continue; } totalAmount += thisStack.getAmount(); } return totalAmount; }
private boolean containsItem( Collection<? extends ItemStack> items, ItemStack item, boolean ingredient) { for (ItemStack i : items) { if (i != null && i.getTypeId() == item.getTypeId() && (item.getDurability() == Vanilla.DATA_WILDCARD || i.getDurability() == item.getDurability()) && (ingredient || item.getAmount() == 1 || item.getAmount() == i.getAmount())) { return true; } } return false; }
@Command( command = "iteminfo", aliases = {"iinfo"}, description = "Shows information about items", syntax = "/iteminfo §2(what's the item in hand?) \n" + "/iteminfo §712§f §2(what's the item with ID §712§2?) \n" + "/iteminfo §7log§f §2(what's the item ID of §7LOG§2?)") public static boolean itemInfo(CommandSender sender, String currentAlias, String[] args) { ItemStack item; if (args.length == 0) { if (!(sender instanceof Player)) { return false; } item = ((Player) sender).getItemInHand(); } else { item = MaterialUtil.getItem(StringUtil.joinArray(args)); } if (item == null || item.getType() == Material.AIR) { return false; } String durability = (item.getDurability() != 0 ? ChatColor.DARK_GREEN + ":" + item.getDurability() : ""); String enchantmentString = MaterialUtil.Enchantments.encodeEnchantment(item.getEnchantments()); String enchantment = (enchantmentString != null ? ChatColor.DARK_AQUA + "-" + enchantmentString : ""); String itemName = MaterialUtil.getName(item); EventUtils.sendMessage(new MessageEvent("iteminfo"), sender); sender.sendMessage( ChatColor.GRAY + itemName + ChatColor.WHITE + " " + item.getTypeId() + durability + enchantment); sendEnchantments(item.getEnchantments(), sender); return true; }
@Override protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception { ItemStack itemStack = null; if (args.length < 1) { if (sender instanceof Player) { itemStack = ((Player)sender).getItemInHand(); } if (itemStack == null) { throw new NotEnoughArgumentsException(); } } else { itemStack = ess.getItemDb().get(args[0]); } sender.sendMessage(itemStack.getType().toString() + "- " + itemStack.getTypeId() + ":" + Integer.toString(itemStack.getData().getData())); if (itemStack.getType() != Material.AIR) { int maxuses = itemStack.getType().getMaxDurability(); int durability = ((maxuses + 1) - itemStack.getDurability()); if (maxuses != 0) { sender.sendMessage(_("durability", Integer.toString(durability))); } } }
public void excute(Minecart minecart, MinecartControl mc, String... job) { if (!(minecart instanceof InventoryHolder) || minecart instanceof PoweredMinecart) { return; } InventoryHolder invMinecart = (InventoryHolder) minecart; HashSet<ItemStack> itemStacks = mc.getUtils().getItemTransferUtil().getItemStacks(job[0]); for (ItemStack itemStack : itemStacks) { if (itemStack.getAmount() == 0) { return; } for (Iterator<Recipe> irt = Bukkit.recipeIterator(); irt.hasNext(); ) { Recipe r = irt.next(); if (r instanceof ShapedRecipe) { ShapedRecipe recipe = ((ShapedRecipe) r); if (recipe.getResult().getType() == itemStack.getType() && recipe.getResult().getDurability() == itemStack.getDurability()) { System.out.println(recipe.getResult().getType().name()); int y = 0; while (y < itemStack.getAmount()) { crafting(recipe, invMinecart); y += recipe.getResult().getAmount(); } } } } } }
@EventHandler public static void onTransactionLogToDB(TransactionEvent event) { if (!Config.getBoolean(LOG_TO_DATABASE) && !Config.getBoolean(GENERATE_STATISTICS_PAGE)) { return; } double pricePerStack = event.getPrice() / event.getStock().length; for (ItemStack item : event.getStock()) { Transaction transaction = new Transaction(); transaction.setAmount(item.getAmount()); transaction.setItemID(item.getTypeId()); transaction.setItemDurability(item.getDurability()); transaction.setPrice((float) pricePerStack); transaction.setShopOwner(event.getOwner().getName()); transaction.setShopUser(event.getClient().getName()); transaction.setSec(System.currentTimeMillis() / 1000); transaction.setBuy(event.getTransactionType() == BUY); Queue.addToQueue(transaction); } }
public void drop(Location loc) { PartyRoom.debug( owner.getName() + " got OwnedItemStack of type " + item.getType() + ":" + item.getDurability() + " at " + Utilities.LocToString(loc)); final Item itemEntity = loc.getWorld().dropItem(loc, item); itemEntity.setMetadata("owner", new FixedMetadataValue(PartyRoom.getPlugin(), owner.getName())); new BukkitRunnable() { int cycle = 0; public void run() { if (itemEntity.isDead() || itemEntity == null) { itemEntity.removeMetadata("owner", PartyRoom.getPlugin()); this.cancel(); return; } if (cycle > 60) { itemEntity.removeMetadata("owner", PartyRoom.getPlugin()); this.cancel(); return; } cycle++; } }.runTaskTimer(PartyRoom.getPlugin(), 20L, 20L); }
@SuppressWarnings({ "rawtypes", "unchecked" }) // I can't parameterize this either; it scares the compiler private static <T extends VariantData<U, T, ?>, U extends CatalogType> T getItemData( ItemStack item, Class<T> type, BiMap<U, Integer> map) { int damage = item.getDurability(); if (!map.containsValue(damage)) { throw new UnsupportedOperationException(); } // no idea why a typecast is necessary here but excluding it makes javac angry @SuppressWarnings("RedundantCast") T data = (T) Pore.getGame() .getRegistry() .createItemBuilder() .itemType(MaterialConverter.asItem(item.getType())) .quantity(1) .build() .getOrCreate(type) .get(); data.type().set(map.inverse().get(damage)); return data; }
private Collection<ItemStack> getStackOnRecipeMatch(final Recipe recipe, final ItemStack stack) { final Collection<ItemStack> inputList; if (recipe instanceof ShapedRecipe) { ShapedRecipe sRecipe = (ShapedRecipe) recipe; inputList = sRecipe.getIngredientMap().values(); } else if (recipe instanceof ShapelessRecipe) { ShapelessRecipe slRecipe = (ShapelessRecipe) recipe; inputList = slRecipe.getIngredientList(); } else { return null; } boolean match = true; Iterator<ItemStack> iter = inputList.iterator(); while (iter.hasNext()) { ItemStack inputSlot = iter.next(); if (inputSlot == null) { iter.remove(); continue; } if (inputSlot.getDurability() == Short.MAX_VALUE) { inputSlot.setDurability((short) 0); } if (!inputSlot.isSimilar(stack)) { match = false; } } if (match) { return inputList; } return null; }
@Override public void serializeItemStack(DataOutputStream output, ItemStack stack) throws IOException { // Speed things up if the workaround is not required if (!isRequired()) { super.serializeItemStack(output, stack); return; } NbtCompound tag = stack != null && stack.getType() != Material.AIR ? NbtFactory.asCompound(NbtFactory.fromItemTag(stack)) : null; // Note that we can't write the stack data directly, as 1.8 switched to sending a // item name instead of an item ID. if (tag != null) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream dataStream = new DataOutputStream(byteStream); ItemStack withoutTag = new ItemStack(stack.getType(), stack.getAmount(), stack.getDurability()); // This will write the stack as normal, without its tag compound and the tag field length super.serializeItemStack(dataStream, withoutTag); output.write(byteStream.toByteArray(), 0, byteStream.size() - 2); serializeCompound(output, tag); } else { // Write the stack as normal super.serializeItemStack(output, stack); } }
/** * Converts specified inventory into inventory string and stores it. Previous inventory string * will be deleted. * * @param playerinv inventory that will be stored */ public void storeInventory(PlayerInventory playerinv) { String inv = ""; for (int i = 0; i < 40; i++) { ItemStack item = playerinv.getItem(i); if (item == null || item.getType() == Material.AIR) continue; String enchantString = ""; for (Entry<Enchantment, Integer> e : item.getEnchantments().entrySet()) enchantString += String.valueOf(e.getKey().getId()) + ":" + String.valueOf(e.getValue()) + "*"; if (enchantString.length() > 1) enchantString = enchantString.substring(0, enchantString.length() - 1); inv += String.valueOf(item.getTypeId()) + "," + String.valueOf(item.getAmount()) + "," + String.valueOf(item.getDurability()) + "," + enchantString + ";"; } inventory = inv; InputOutput.UpdatePrisoner(this); }
/** * Apply the hard stone game mechanic * * <p>Players who mine stone below a certain depth increase their hunger * * @param blockY The Y coordinate of the mined block * @param tool The tool that was used to mine the block */ public void doHardStone(int blockY, ItemStack tool) { // Calculate applicable durability penalty short penalty; if (tool.getType() == Material.GOLD_PICKAXE) { penalty = UhcMatch.DURABILITY_PENALTY_GOLD; } else if (tool.getType() == Material.WOOD_PICKAXE) { penalty = UhcMatch.DURABILITY_PENALTY_WOOD; } else if (tool.getType() == Material.STONE_PICKAXE) { penalty = UhcMatch.DURABILITY_PENALTY_STONE; } else if (tool.getType() == Material.IRON_PICKAXE) { penalty = UhcMatch.DURABILITY_PENALTY_IRON; } else if (tool.getType() == Material.DIAMOND_PICKAXE) { penalty = UhcMatch.DURABILITY_PENALTY_DIAMOND; } else return; // Warn the player the first time if (!warnedHardStone) { player.sendMessage( ChatColor.GOLD + "Warning! Mining smoothstone will wear out your tools more quickly than in normal Minecraft."); warnedHardStone = true; } // Apply durability cost tool.setDurability((short) (tool.getDurability() + penalty)); }
public void updateSpectatorOnInventory(Player spec) { Player player = getPlayer().getPlayer(); if (player == null) return; PlayerInventory inv = player.getInventory(); int goldIngots = 0; int goldenApples = 0; int notchApples = 0; for (ItemStack is : inv.getContents()) { if (is != null) { if (is.getType() == Material.GOLD_INGOT) goldIngots += is.getAmount(); if (is.getType() == Material.GOLD_BLOCK) goldIngots += is.getAmount() * 9; if (is.getType() == Material.GOLD_NUGGET) goldIngots += is.getAmount() / 9; if (is.getType() == Material.GOLDEN_APPLE) { if (is.getDurability() == 0) goldenApples += is.getAmount(); if (is.getDurability() == 1) notchApples += is.getAmount(); } } } PluginChannelUtils.messageSpectator( spec, "player", getName(), "itemcount", "266", Integer.toString(goldIngots)); PluginChannelUtils.messageSpectator( spec, "player", getName(), "itemcount", "322,0", Integer.toString(goldenApples)); PluginChannelUtils.messageSpectator( spec, "player", getName(), "itemcount", "322,1", Integer.toString(notchApples)); }
@SuppressWarnings("deprecation") @Override protected void execute(Event e) { Location pos1 = location1.getSingle(e); Location pos2 = location2.getSingle(e); EditSession session = editSession.getSingle(e); ItemStack[] blocks = blockList.getAll(e); RandomPattern random = new RandomPattern(); if (session == null) return; for (ItemStack b : blocks) { if (b.getType().isBlock()) { random.add(new BlockPattern(new BaseBlock(b.getTypeId(), b.getDurability())), 50); } } try { session.makeWalls( new CuboidRegion( (World) BukkitUtil.getLocalWorld(pos1.getWorld()), BukkitUtil.toVector(pos1), BukkitUtil.toVector(pos2)), Patterns.wrap(random)); session.flushQueue(); } catch (WorldEditException ex) { if (ex instanceof MaxChangedBlocksException) return; else ex.printStackTrace(); } }
public void removePearlFromContainer(PrisonPearl pp) { Inventory inv[] = new Inventory[2]; if (HolderStateToInventory(pp, inv) != HolderStateToInventory_SUCCESS) { return; } Inventory real_inv = null; int pearlslot = -1; int pp_id = pp.getID(); for (int inv_idx = 0; inv_idx <= 1 && pearlslot == -1; ++inv_idx) { if (inv[inv_idx] == null) { continue; } HashMap<Integer, ? extends ItemStack> inv_contents = inv[inv_idx].all(Material.ENDER_PEARL); for (int inv_slot : inv_contents.keySet()) { ItemStack slot_item = inv_contents.get(inv_slot); if (slot_item.getDurability() == pp_id) { real_inv = inv[inv_idx]; pearlslot = inv_slot; break; } } } if (real_inv == null || pearlslot == -1) { return; } real_inv.setItem(pearlslot, new ItemStack(Material.ENDER_PEARL)); }
public static Potion fromItemStack(ItemStack item) { Validate.notNull(item, "item cannot be null"); if (item.getType() != Material.POTION) { throw new IllegalArgumentException("item is not a potion"); } return fromDamage(item.getDurability()); }
// Returns true if this ingredient cares about durability public boolean hasExactData(ItemStack item) { for (ItemStack ingredient : ingredients) { if (ingredient.getType().equals(item.getType())) { return ingredient.getDurability() != -1; } } return true; }
@Override public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding) { GlowBanner banner = (GlowBanner) block.getState(); banner.setBase(DyeColor.getByDyeData((byte) holding.getDurability())); BannerMeta meta = (BannerMeta) holding.getItemMeta(); banner.setPattern(meta.getPattern()); banner.update(); }
private ItemStack cloneItemStack(ItemStack source) { if (source == null) { // sanity check return null; } return new ItemStack( source.getType(), source.getAmount(), source.getDurability(), (source.getData() != null ? source.getData().getData() : null)); }
/** * Creates a new item stack derived from the specified stack * * @param stack the stack to copy * @throws IllegalArgumentException if the specified stack is null or returns an item meta not * created by the item factory */ public ItemStack(final ItemStack stack) throws IllegalArgumentException { Validate.notNull(stack, "Cannot copy null stack"); this.type = stack.getTypeId(); this.amount = stack.getAmount(); this.durability = stack.getDurability(); this.data = stack.getData(); if (stack.hasItemMeta()) { setItemMeta0(stack.getItemMeta(), getType0()); } }
/** * Check if the ItemStack is a Drug * * @param item The ItemStack * @return If the ItemStack is a Drug */ public boolean isDrug(ItemStack item) { for (Drug drug : getDrugs()) { Material mat = drug.getItemStack().getType(); short dmg = drug.getItemStack().getDurability(); if (mat.name().equalsIgnoreCase(item.getType().name()) && dmg == item.getDurability()) { return true; } } return false; }
/** * Get Drug instance from ItemStack * * @param item The ItemStack * @return The Drug instance */ public Drug getDrug(ItemStack item) { for (Drug drug : getDrugs()) { Material drugMat = drug.getItemStack().getType(); short drugDmg = drug.getItemStack().getDurability(); if (drugMat == item.getType() && drugDmg == item.getDurability()) { return drug; } } return null; }
@SuppressWarnings("deprecation") public void run() { for (Player p : c.getServer().getOnlinePlayers()) { for (ItemStack is : p.getInventory().getContents()) { if (is == null || is.getType() == Material.AIR || !is.hasItemMeta()) continue; if (!is.getItemMeta().hasLore()) continue; if (!c.hasCustomEnchant(is.getItemMeta().getLore())) continue; boolean b = false; for (String s : is.getItemMeta().getLore()) { if (!c.isCustomEnchant(s)) continue; if (s.startsWith(ChatColor.RESET + "Repair ")) b = true; } if (!b) continue; if (is.getDurability() > 0) is.setDurability((short) (is.getDurability() - 1)); } boolean hasChestplateOn = false; for (ItemStack is : p.getInventory().getArmorContents()) { if (is == null || !is.getType().name().endsWith("CHESTPLATE") || !is.hasItemMeta()) continue; if (!is.getItemMeta().hasLore()) continue; if (!c.hasCustomEnchant(is.getItemMeta().getLore())) continue; boolean b = false; for (String s : is.getItemMeta().getLore()) { if (!c.isCustomEnchant(s)) continue; if (s.startsWith(ChatColor.RESET + "Flying ")) b = true; } if (!b) continue; if (!hasChestplateOn) { if (!p.isFlying()) { p.sendMessage(ChatColor.GOLD + "Flying enabled!"); } p.setAllowFlight(true); p.setFlying(true); hasChestplateOn = true; } } if (!hasChestplateOn && p.getGameMode() != GameMode.CREATIVE && p.isFlying()) { p.setFlying(false); p.setAllowFlight(false); } } }
/** * Get a block. * * @param id */ @Override public void fetchItem(BaseItem item) throws BlockBagException { final int id = item.getType(); final int damage = item.getDamage(); int amount = (item instanceof BaseItemStack) ? ((BaseItemStack) item).getAmount() : 1; assert (amount == 1); boolean usesDamageValue = ItemType.usesDamageValue(id); if (id == BlockID.AIR) { throw new IllegalArgumentException("Can't fetch air block"); } loadInventory(); boolean found = false; for (int slot = 0; slot < items.length; ++slot) { ItemStack bukkitItem = items[slot]; if (bukkitItem == null) { continue; } if (bukkitItem.getTypeId() != id) { // Type id doesn't fit continue; } if (usesDamageValue && bukkitItem.getDurability() != damage) { // Damage value doesn't fit. continue; } int currentAmount = bukkitItem.getAmount(); if (currentAmount < 0) { // Unlimited return; } if (currentAmount > 1) { bukkitItem.setAmount(currentAmount - 1); found = true; } else { items[slot] = null; found = true; } break; } if (!found) { throw new OutOfBlocksException(); } }
private void repairItem(final ItemStack item) throws Exception { final Material material = Material.getMaterial(item.getTypeId()); if (material.isBlock() || material.getMaxDurability() < 0) { throw new Exception(Util.i18n("repairInvalidType")); } if (item.getDurability() == 0) { throw new Exception(Util.i18n("repairAlreadyFixed")); } item.setDurability((short) 0); }
public static void transferDamage(ItemStack stack, JsonObject json, boolean stack2json) { // Durability is a weird name since it is the amount of damage. if (stack2json) { int damage = stack.getDurability(); if (damage == DEFAULT_DAMAGE) return; json.addProperty(DAMAGE, damage); } else { JsonElement element = json.get(DAMAGE); if (element == null) return; stack.setDurability(element.getAsShort()); } }
/** * add an ItemStack to an array * * @param items * @param toAdd * @param extraStack whether to allow some nonstackable items to stack * @return */ public static ItemStack add(ItemStack[] items, ItemStack toAdd, boolean extraStack) { ItemStack ret = toAdd.clone(); int mx = !extraStack || noStack.contains(toAdd.getTypeId()) ? JItems.getMaxStack(toAdd) : 64; boolean firstRun = true; for (int i = 0; i < items.length; ++i) { if (!firstRun && (items[i] == null || items[i].getAmount() == 0)) { if (items[i] == null) { items[i] = toAdd; } else { items[i].setTypeId(toAdd.getTypeId()); items[i].setDurability(toAdd.getDurability()); items[i].addEnchantments(toAdd.getEnchantments()); } items[i].setAmount(ret.getAmount()); ret.setAmount(0); return ret; } else if (items[i] != null && items[i].getTypeId() == toAdd.getTypeId() && items[i].getDurability() == toAdd .getDurability() // (!JItems.hasData(toAdd.getTypeId()) || // items[i].getData().getData() == toAdd.getData().getData()) && sameEnchants(items[i], toAdd) && items[i].getAmount() < mx) { // on first run, look for other stacks in array that could be incremented instead if (items[i].getAmount() + ret.getAmount() <= mx) { items[i].setAmount(items[i].getAmount() + ret.getAmount()); ret.setAmount(0); return ret; } else { ret.setAmount(ret.getAmount() - (mx - items[i].getAmount())); items[i].setAmount(mx); } } else if (firstRun && i + 1 >= items.length) { firstRun = false; i = -1; // negative, because gets incremented again } } return ret; }