public CraftWrittenBook(ItemStack itemstack) throws Exception { if (itemstack.getTypeId() != 387) { throw new Exception("Expected type id 387, got " + itemstack.getTypeId()); } this.bookMeta = (BookMeta) itemstack.getItemMeta(); }
/** * 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) { int amt = toAdd.getAmount(); 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)) { items[i] = toAdd; items[i].setAmount(amt); return items; } else if (items[i] != null && items[i].getTypeId() == toAdd.getTypeId() && (!JItems.hasData(toAdd.getTypeId()) || items[i].getData().getData() == toAdd.getData().getData()) && items[i].getAmount() < mx) { // on first run, look for other stacks in array that could be incremented instead if (items[i].getAmount() + amt <= mx) { items[i].setAmount(items[i].getAmount() + amt); return items; } else { amt -= 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 items; }
/** * Figure out how much of a given item is in the player's inventory * * @param player The player entity in question. * @param id The Data Value of the item in question. * @return The amount of the item in the player's inventory as an integer. */ public int getAmountInInventory(Player player, ItemStack it) { int inInventory = 0; int x = 0; ItemStack slot; // we do it this way incase a user has an expanded inventory via another plugin for (@SuppressWarnings("unused") ItemStack stack : player.getInventory().getContents()) { slot = player.getInventory().getItem(x); if (slot != null) { Byte slotData = Byte.valueOf("0"); Byte itData = Byte.valueOf("0"); try { slotData = slot.getData().getData(); } catch (NullPointerException e) { } try { itData = it.getData().getData(); } catch (NullPointerException e) { } if ((slot.getTypeId() == it.getTypeId()) && (slotData.compareTo(itData) == 0)) { inInventory += slot.getAmount(); } } /*else { return 0; }*/ x++; } return inInventory; }
@Override public int compare(ItemStack a, ItemStack b) { final int aType = a.getTypeId(), bType = b.getTypeId(); if (aType < bType) return -1; if (aType > bType) return 1; final short aData = rawData(a), bData = rawData(b); if (aData < bData) return -1; if (aData > bData) return 1; return 0; }
/* * Called when a block is broken. */ @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Player player = event.getPlayer(); WorldConfiguration wcfg = getWorldConfig(player); if (!wcfg.itemDurability) { ItemStack held = player.getItemInHand(); if (held.getTypeId() > 0 && !(ItemType.usesDamageValue(held.getTypeId()) || BlockType.usesData(held.getTypeId()))) { held.setDurability((short) 0); player.setItemInHand(held); } } if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock()) || !plugin.getGlobalRegionManager().canConstruct(player, event.getBlock())) { player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area."); event.setCancelled(true); return; } if (wcfg.getBlacklist() != null) { if (!wcfg.getBlacklist() .check( new BlockBreakBlacklistEvent( plugin.wrapPlayer(player), toVector(event.getBlock()), event.getBlock().getTypeId()), false, false)) { event.setCancelled(true); return; } if (!wcfg.getBlacklist() .check( new DestroyWithBlacklistEvent( plugin.wrapPlayer(player), toVector(event.getBlock()), player.getItemInHand().getTypeId()), false, false)) { event.setCancelled(true); return; } } if (wcfg.isChestProtected(event.getBlock(), player)) { player.sendMessage(ChatColor.DARK_RED + "The chest is protected."); event.setCancelled(true); return; } }
public void handleList(Chest chest, Player p) { ItemStack[] is = chest.getInventory().getContents(); for (ItemStack i : is) { if (i != null) { p.sendMessage("i= " + i.getTypeId()); handlePayment(p, getPrice(i.getTypeId())); items.add(i.getType()); } } }
public static boolean hasFirelordArmor(Player player) { ItemStack helm = player.getInventory().getHelmet(); ItemStack breast = player.getInventory().getChestplate(); ItemStack legs = player.getInventory().getLeggings(); if ((helm.getTypeId() == Config.getHelmId()) && (breast.getTypeId() == Config.getChestId()) && (legs.getTypeId() == Config.getLegsId())) { return true; } else return false; }
public void setPowertool(ItemStack stack, List<String> commandList) { if (commandList == null || commandList.isEmpty()) { powertools.remove("" + stack.getTypeId()); } else { powertools.put("" + stack.getTypeId(), commandList); } config.setProperty("powertools", powertools); config.save(); }
public void setUnlimited(ItemStack stack, boolean state) { if (unlimited.contains(stack.getTypeId())) { unlimited.remove(Integer.valueOf(stack.getTypeId())); } if (state) { unlimited.add(stack.getTypeId()); } config.setProperty("unlimited", unlimited); config.save(); }
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; }
@Override public boolean onRightClick(ItemStack itemInHand) { // right click toggling is enabled, handle it and check permission if (TGlobalSettings.mmRightToggle() && perms.has(player, "dtl.trader.manage")) { // if air then chane to stick item ItemStack itemToToggle = TGlobalSettings.mmItemToggle(); if (itemToToggle.getType().equals(Material.AIR)) itemToToggle.setType(Material.STICK); // if id's in hand and for toggling are the same manage the mode change if (itemInHand != null && itemToToggle.getTypeId() == itemInHand.getTypeId()) { // send a event when manager mode toggling TraderClickEvent e = (TraderClickEvent) new TraderClickEvent(this, player, true, false).callEvent(); // we can still stop mmToggling if (e.isManagerToggling()) { toggleManageMode("right"); // stop event execution return false; } } else { // maybe we can do this bit more nicer? // send a event withoug toggling new TraderClickEvent(this, player, false, false).callEvent(); } } else { // send a event withoug toggling new TraderClickEvent(this, player, false, false).callEvent(); } // debug info dB.info(this.getClass().getSimpleName(), " Trader right click event, by: ", player.getName()); if (status.inManagementMode()) inventory = stock.getManagementInventory(baseStatus, status); else inventory = stock.getInventory(status); parseStatus(status); updatePlayerInventory(); // register the inventory as a traderInventory tNpcManager.instance().registerOpenedInventory(player, inventory); // open the traders inventory player.openInventory(inventory); return true; }
@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); } }
@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))); } } }
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL) public void onPlayerInteract(PlayerInteractEvent event) { if (event.isCancelled()) return; final Player player = event.getPlayer(); final Block block = event.getClickedBlock(); final ItemStack item = event.getItem(); if (player.getWorld() != plugin.getIslandWorld()) return; if (player.isOp()) return; if (player.hasPermission("islandworld.bypass.island")) return; if (block != null) { final Material t = block.getType(); plugin.debug("Interact with block: " + t.getId() + " : " + block); if (!(plugin.getConfig().getBoolean("flags.use-switches", false) && isSwitch(t))) { if (!(isOnAllowedList(t) || plugin.canBuildOnLocation(player, block.getLocation()))) event.setCancelled(true); } } else { if (item != null) { plugin.debug("Using item: " + item.getTypeId()); if (!(isOnAllowedList(item.getType()) || plugin.canBuildOnLocation(player, player.getLocation()))) event.setCancelled(true); } } plugin.debug("Event :" + event.getEventName() + ", cancelled:" + event.isCancelled()); }
@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(); } }
@Override public void upgrade(Arena arena, Player p) { if (item == null) return; ItemStack[] items = p.getInventory().getContents(); int firstEmpty = -1; // Find a matching ID and upgrade it for (int i = 0; i < 9; i++) { // Save the first null index if (items[i] == null) { if (firstEmpty < 0) firstEmpty = i; continue; } // If we find an ID, upgrade and quit if (items[i].getTypeId() == item.getTypeId()) { items[i] = item; p.getInventory().setContents(items); return; } } // If nothing was found, just give them a new weapon if (firstEmpty > 0) { items[firstEmpty] = item; p.getInventory().setContents(items); } else { p.getInventory().addItem(item); } }
// ================================================================================================ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerItemHeld(PlayerItemHeldEvent event) { try { if ((event.getPlayer().hasPermission("arctica.use")) && (!event.getPlayer().hasPermission("arctica.immune"))) { ItemStack newItem; newItem = event.getPlayer().getInventory().getItem(event.getNewSlot()); if ((null != newItem) && (newItem.getTypeId() == 50)) // Check if held item is a torch. Is null if empty slot. { if ((plugin.playerIsAffected(event.getPlayer())) && (!playersHoldingTorch.contains(event.getPlayer().getName()))) { // if(Arctica.debug){event.getPlayer().sendMessage(ChatColor.GREEN + "Fackel-Bonus // EIN.");} playersHoldingTorch.add(event.getPlayer().getName()); } } else // Player with permission has no torch in hand, so delete him from the List if he's // on it. { // This should always be done, even if the player is currently not affected, to prevent // exploiting the mechanism // Through leaving the cold biome if (playersHoldingTorch.contains(event.getPlayer().getName())) { // if(Arctica.debug){event.getPlayer().sendMessage(ChatColor.GREEN + "Fackel-Bonus // AUS.");} playersHoldingTorch.remove(event.getPlayer().getName()); } } } } catch (Exception ex) { // player is probably no longer online } }
public ItemType CheckItem(ItemStack stack) throws InvocationTargetException, IllegalAccessException { int ItemID = stack.getTypeId(); byte meta = stack.getData().getData(); Object item = nmsResolver.getItemList().get(ItemID); ForgePermittor.log(item.toString(), true); if (item != null) { /* if (this.getInformationManager().HasConnectableInferface(item)) return ItemType.Connectable;*/ if (this.getInformationManager().HasItemBlockContainerInterface(item)) return ItemType.Container; if (this.getInformationManager().HasFoodInterface(item)) return ItemType.Food; if (this.getInformationManager().HasSwordInterface(item)) return ItemType.Weapon; if (this.getInformationManager().HasItemBlockInterface(item)) return CheckItemBlock(item, ItemID, meta); if (this.getInformationManager().HasItemInterface(item)) { if (nmsResolver .getItemStackHandler() .HasTagCompound(nmsResolver.getCraftItemStackHandler().asNMSCopy(stack))) return ItemType.AdvItem; return ItemType.Item; } } return ItemType.Unknown; }
double getTotalWeight(Player player) { double modifier = 0; for (ItemStack i : player.getInventory().getArmorContents()) { if (i != null) modifier += weight(i.getTypeId()); } return modifier; }
public static PlayerDeathEvent callPlayerDeathEvent( EntityPlayer victim, List<org.bukkit.inventory.ItemStack> drops, String deathMessage) { BukkitPlayer entity = (BukkitPlayer) getBukkitEntity(victim); PlayerDeathEvent event = new PlayerDeathEvent(entity, drops, victim.experienceValue, 0, deathMessage); org.bukkit.World world = entity.getWorld(); Bukkit.getServer().getPluginManager().callEvent(event); /*victim.keepLevel = event.getKeepLevel(); victim.newLevel = event.getNewLevel(); victim.newTotalExp = event.getNewTotalExp(); victim.expToDrop = event.getDroppedExp(); victim.newExp = event.getNewExp();*/ for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { if (stack == null || stack.getType() == Material.AIR) continue; if (stack instanceof BukkitItemStack) { // Use the internal item to preserve possible data. victim.dropItemWithOffset(stack.getTypeId(), stack.getAmount(), 0.0F); } else { world.dropItemNaturally(entity.getLocation(), stack); } } return event; }
public ItemStack setEnchantments(ItemStack item, String enchants) { ItemStack i = item.clone(); if (enchants.isEmpty()) return i; String[] ln = enchants.split(","); for (String ec : ln) { if (ec.isEmpty()) continue; Color clr = colorByName(ec); if (clr != null) { if (isIdInList(item.getTypeId(), "298,299,300,301")) { LeatherArmorMeta meta = (LeatherArmorMeta) i.getItemMeta(); meta.setColor(clr); i.setItemMeta(meta); } } else { String ench = ec; int level = 1; if (ec.contains(":")) { ench = ec.substring(0, ec.indexOf(":")); level = Math.max(1, getMinMaxRandom(ec.substring(ench.length() + 1))); } Enchantment e = Enchantment.getByName(ench.toUpperCase()); if (e == null) continue; i.addUnsafeEnchantment(e, level); } } return i; }
/** * 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); }
public static boolean is_full(ItemStack[] items, int check, boolean extraStack) { int amt = 1; for (ItemStack item : items) { int mx = !extraStack || noStack.contains(item == null ? 0 : item.getTypeId()) ? JItems.getMaxStack(item) : 64; if (item == null || item.getAmount() == 0 || (item.getTypeId() == check && (item.getAmount() + amt <= mx))) { return false; } else if (item.getTypeId() == check) { amt -= mx - item.getAmount(); } } return true; }
private Stockable getStockable(ItemStack item, String keyword, boolean selling) { // durability needs to be reset to 0 for tools / weapons / armor short durability = item.getDurability(); if (isTool(item.getTypeId())) { durability = 0; } TraderNPC trader = npc.getToggleable("trader"); if (!trader.isStocked(item.getTypeId(), durability, selling)) { player.sendMessage( StringUtils.wrap(MessageUtils.getItemName(item.getTypeId()), ChatColor.RED) + " isn't being " + keyword + " here."); return null; } return trader.getStockable(item.getTypeId(), durability, selling); }
public static net.minecraft.src.ItemStack createNMSItemStack(ItemStack original) { if (original == null || original.getTypeId() <= 0) { return null; } else if (original instanceof BukkitItemStack) { return ((BukkitItemStack) original).getHandle(); } return new BukkitItemStack(original).getHandle(); }
@Override public void setResult(ItemStack item) { net.minecraft.server.v1_6_R3.ItemStack[] contents = this.result.getContents(); if (item == null || item.getTypeId() <= 0) { contents[0] = null; } else { contents[0] = CraftItemStack.asNMSCopy(item); } }
/** * Validate that an item has a durability and can be repaired * * @param item * @return */ public static boolean isTool(ItemStack item) { int id = item.getTypeId(); return (id >= 256 && id <= 259) || (id >= 267 && id <= 279) || (id >= 283 && id <= 286) || (id >= 290 && id <= 294) || id == 346 || id == 359; }
public static ItemStack[] compressInventory(ItemStack[] items) { final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>(); for (final ItemStack item : items) if (item != null) { final int type = item.getTypeId(); final short data = rawData(item); boolean found = false; for (final ItemStack item2 : compressed) if (type == item2.getTypeId() && data == rawData(item2)) { item2.setAmount(item2.getAmount() + item.getAmount()); found = true; break; } if (!found) compressed.add(new ItemStack(type, item.getAmount(), data)); } Collections.sort(compressed, new ItemStackComparator()); return compressed.toArray(new ItemStack[compressed.size()]); }
/** * Instantiates a new item projectile. * * @param name projectile name * @param loc location of projectile (sets position of projectile and shoots in pitch and yaw * direction) * @param itemstack item stack to shoot * @param shooter projectile shooter * @param power projectile power */ @SuppressWarnings("deprecation") public ItemProjectile( String name, Location loc, org.bukkit.inventory.ItemStack itemstack, LivingEntity shooter, float power) { super(((CraftWorld) loc.getWorld()).getHandle(), loc.getX(), loc.getY(), loc.getZ(), null); if (CraftItemStack.asNMSCopy(itemstack) != null) setItemStack(CraftItemStack.asNMSCopy(itemstack)); else setItemStack( new net.minecraft.server.v1_8_R1.ItemStack( Item.getById(itemstack.getTypeId()), itemstack.getAmount(), itemstack.getData().getData())); if (itemstack.getTypeId() == 0) System.out.println("You cannot shoot air!"); this.name = name; this.pickupDelay = Integer.MAX_VALUE; this.shooter = ((CraftLivingEntity) shooter).getHandle(); this.a(0.25F, 0.25F); setPositionRotation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); locX -= (MathHelper.cos(yaw / 180.0F * 3.1415927F) * 0.16F); locY -= 0.10000000149011612D; locZ -= (MathHelper.sin(yaw / 180.0F * 3.1415927F) * 0.16F); setPosition(locX, locY, locZ); float f = 0.4F; motX = (-MathHelper.sin(yaw / 180.0F * 3.1415927F) * MathHelper.cos(pitch / 180.0F * 3.1415927F) * f); motZ = (MathHelper.cos(yaw / 180.0F * 3.1415927F) * MathHelper.cos(pitch / 180.0F * 3.1415927F) * f); motY = (-MathHelper.sin(pitch / 180.0F * 3.1415927F) * f); shoot(motX, motY, motZ, power * 1.5F, 1.0F); world.addEntity(this); try { this.f = Entity.class.getDeclaredField("invulnerable"); } catch (NoSuchFieldException e) { e.printStackTrace(); } }
/** * 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()); } }