@Override protected void onInventoryClick(InventoryClickEvent event, Player player) { event.setCancelled(true); final int slot = event.getRawSlot(); if (slot >= 0 && slot <= 7) { // handle changing sell stack size ItemStack item = event.getCurrentItem(); if (item != null && item.getType() != Material.AIR) { int amount = item.getAmount(); amount = this.getNewAmountAfterEditorClick(event, amount); if (amount <= 0) amount = 1; if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize(); item.setAmount(amount); } } else if ((slot >= 9 && slot <= 16) || (slot >= 18 && slot <= 25)) { if (((TradingPlayerShopkeeper) shopkeeper).clickedItem != null) { // placing item final Inventory inventory = event.getInventory(); Bukkit.getScheduler() .runTaskLater( ShopkeepersPlugin.getInstance(), new Runnable() { public void run() { inventory.setItem(slot, ((TradingPlayerShopkeeper) shopkeeper).clickedItem); ((TradingPlayerShopkeeper) shopkeeper).clickedItem = null; } }, 1); } else { // changing stack size ItemStack item = event.getCurrentItem(); if (item != null && item.getType() != Material.AIR) { int amount = item.getAmount(); amount = this.getNewAmountAfterEditorClick(event, amount); if (amount <= 0) { event.getInventory().setItem(slot, null); } else { if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize(); item.setAmount(amount); } } } } else if (slot >= 27) { // clicking in player inventory if (event.isShiftClick() || !event.isLeftClick()) { return; } ItemStack cursor = event.getCursor(); if (cursor != null && cursor.getType() != Material.AIR) { return; } ItemStack current = event.getCurrentItem(); if (current != null && current.getType() != Material.AIR) { ((TradingPlayerShopkeeper) shopkeeper).clickedItem = current.clone(); ((TradingPlayerShopkeeper) shopkeeper).clickedItem.setAmount(1); } } else { super.onInventoryClick(event, player); } }
private int findSpace( ItemStack item, Map<Integer, StackWithAmount> lookaside, boolean findEmpty) { // 1.9.4 and later extend living entity slots beyond 36, but some of these are read-only. // We could use .getStorageContents(), but this breaks 1.8.8 compatibility int length = (inventory.getHolder() instanceof HumanEntity) ? 36 : inventory.getSize(); ItemStack[] stacks = Arrays.copyOfRange(inventory.getContents(), 0, length); if (item == null) { return -1; } for (int i = 0; i < stacks.length; i++) { boolean contains = lookaside.containsKey(i); if (findEmpty && !contains) { return i; } else if (!findEmpty && contains) { StackWithAmount compareWith = lookaside.get(i); if (compareWith != null) { ItemStack compareWithStack = compareWith.getStack(); if (compareWith.getAmount() < compareWithStack.getMaxStackSize() && compareWithStack.isSimilar(item)) { return i; } } } } return -1; }
/** * Returns true is the item stack is not null, if the item is a full sized stack, with size more * than one (to prevent simply adding lore to single items), that the item does NOT have lore, and * that the item has simple metadata (not a book, fireworks, banners, beacons, other "special" * items that generate a host of edge cases like duplication and cheap dye and other problems.) * * @param is the ItemStack to check validity of compaction * @return true if can be compacted, false otherwise */ private boolean canCompact(ItemStack is) { return is != null && is.getAmount() == is.getMaxStackSize() && is.getAmount() > 1 && !is.getItemMeta().hasLore() && is.getItemMeta().getClass().getSuperclass().equals(java.lang.Object.class); /* bit of a hack at the end, but effectively only items with "simple" meta, where the implementation * is strictly a subclass of Object, and not a subclass of bukkit's CraftMetaItem. */ }
/** * Sets the player's current help item amount to the specified value * * @param player * @param amount */ private void moar(Player player, int amount) { if (player.getItemInHand().getType() != Material.AIR) { ItemStack itemInHand = player.getItemInHand(); // If amount is too large, set to maxStackSize instead int amtToGive = Math.min(amount, itemInHand.getMaxStackSize()); itemInHand.setAmount(amtToGive); // Continue until full amount has been disbursed amount -= amtToGive; while (amtToGive < amount) { amtToGive -= amount; player .getWorld() .dropItemNaturally( player.getLocation(), new ItemStack( itemInHand.getTypeId(), Math.min(amtToGive, itemInHand.getMaxStackSize()))); } } }
// create/split item stack private ItemStack getSplitItemStack( int itemRowId, int itemId, short itemDamage, int qty, String enchStr) { ItemStack stack = new ItemStack(itemId, qty, itemDamage); int maxSize = stack.getMaxStackSize(); // split stack if (qty > maxSize) { Connection conn = WebAuctionPlus.dataQueries.getConnection(); PreparedStatement st = null; while (qty > maxSize) { try { if (WebAuctionPlus.isDebug()) WebAuctionPlus.log.info( "WA Query: getSplitItemStack qty:" + Integer.toString(qty) + " max:" + Integer.toString(maxSize)); st = conn.prepareStatement( "INSERT INTO `" + WebAuctionPlus.dataQueries.dbPrefix() + "Items` ( " + "`playerName`, `itemId`, `itemDamage`, `qty`, `enchantments` )VALUES( ?, ?, ?, ?, ? )"); st.setString(1, playerName); st.setInt(2, itemId); st.setShort(3, itemDamage); st.setInt(4, maxSize); st.setString(5, enchStr); st.executeUpdate(); } catch (SQLException e) { WebAuctionPlus.log.warning( WebAuctionPlus.logPrefix + "Unable to insert new item to inventory!"); e.printStackTrace(); return null; } finally { WebAuctionPlus.dataQueries.closeResources(st, null); } qty -= maxSize; } stack.setAmount(qty); WebAuctionPlus.dataQueries.closeResources(conn); } // add enchantments if (enchStr != null && !enchStr.isEmpty()) DataQueries.decodeEnchantments(Bukkit.getPlayer(playerName), stack, enchStr); return stack; }
/** Define a quantidade maxima para o item. */ public ItemBuilder maxAmount() { return amount(item.getMaxStackSize()); }
@EventHandler public void playerInteract(PlayerInteractEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); if (player.hasPermission(BannerEditorCommand.PERMISSION) && player.getItemInHand().getType().equals(Material.STICK)) { BlockState state = event.getClickedBlock().getState(); if (state instanceof Banner) { Banner banner = (Banner) state; BannerEditorConfig config = BannerEditorCommand.getPlayerConfig(event.getPlayer()); BannerEditorMode mode = config.getEditorMode(); int patternId = config.getPatternId(); switch (mode) { case LIST: sendBannerInfoMessage(player, banner); break; case TEXTURE: if (patternId > 0 && patternId <= banner.numberOfPatterns()) { banner.setPattern( patternId - 1, new Pattern( banner.getPattern(patternId - 1).getColor(), (PatternType) cycle(banner.getPattern(patternId - 1).getPattern(), event.getAction()))); banner.update(true, false); } else if (patternId == 0) { sendNoPattern(player); } else { sendInvalidPatternId(player, patternId); } break; case COLOR: if (patternId > 0 && patternId <= banner.numberOfPatterns()) { banner.setPattern( patternId - 1, new Pattern( (DyeColor) cycle(banner.getPattern(patternId - 1).getColor(), event.getAction()), banner.getPattern(patternId - 1).getPattern())); banner.update(true, false); } else if (patternId == 0) { banner.setBaseColor((DyeColor) cycle(banner.getBaseColor(), event.getAction())); banner.update(true, false); } else { sendInvalidPatternId(player, patternId); } break; case ADD: banner.addPattern(new Pattern(DyeColor.WHITE, PatternType.CIRCLE_MIDDLE)); banner.update(true, false); break; case REMOVE: if (patternId > 0 && patternId <= banner.numberOfPatterns()) { Pattern pat = banner.removePattern(patternId - 1); banner.update(true, false); } else if (patternId == 0) { sendBaseNoPattern(player); } else { sendInvalidPatternId(player, patternId); } break; case GET: ItemStack item = new ItemStack(Material.BANNER); BannerMeta meta = (BannerMeta) item.getItemMeta(); meta.setBaseColor(banner.getBaseColor()); for (Pattern pattern : banner.getPatterns()) { meta.addPattern(pattern); } item.setItemMeta(meta); int amount = item.getMaxStackSize(); item.setAmount(amount); player.getInventory().addItem(item); sendGotBanner(player, amount); } event.setCancelled(true); } } }
@Override public boolean execute(CommandSender sender, String[] args, Location location) { ArrayList<Inventory> inventoryList = new ArrayList<Inventory>(); if ((args[0].startsWith("@l[") && args[0].endsWith("]")) || inventorySubs.containsKey(args[0])) { Location invLocation = LogiBlocksMain.parseLocation(args[0], location); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Block testBlock = invLocation.clone().add(x, y, z).getBlock(); if (testBlock.getState() instanceof InventoryHolder) { inventoryList.add(((InventoryHolder) testBlock.getState()).getInventory()); } } } } } else { Player player = Bukkit.getPlayer(args[0]); if (player == null) { return false; } inventoryList.add(player.getInventory()); } int subIndex = inventorySubs.containsKey(args[0]) ? 0 : 1; if (!inventorySubs.containsKey(args[subIndex])) { return false; } if (inventorySubs.get(args[subIndex]) + subIndex + 1 > args.length) { return false; } for (Inventory inventory : inventoryList) { switch (args[subIndex]) { case "add": for (int i = subIndex + 1; i < args.length; i++) { ItemStack item1 = LogiBlocksMain.parseItemStack(args[i]); if (item1 == null) { continue; } inventory.addItem(item1); } break; case "remove": for (int i = subIndex + 1; i < args.length; i++) { ItemStack removeItem = LogiBlocksMain.parseItemStack(args[i]); if (removeItem == null) { continue; } for (ItemStack targetItem : inventory.getContents()) { if (targetItem == null) { continue; } if (targetItem.isSimilar(removeItem)) { if (removeItem.getAmount() > targetItem.getAmount()) { removeItem.setAmount(removeItem.getAmount() - targetItem.getAmount()); inventory.remove(removeItem); } else { targetItem.setAmount(targetItem.getAmount() - removeItem.getAmount()); break; } } } } break; case "removeall": for (int i = subIndex + 1; i < args.length; i++) { ItemStack removeItem = LogiBlocksMain.parseItemStack(args[i]); for (int j = 1; j <= 64; j++) { removeItem.setAmount(j); inventory.remove(removeItem); } } break; case "clear": inventory.clear(); break; case "refill": for (ItemStack itemStack : inventory.getContents()) { if (itemStack == null) { continue; } itemStack.setAmount( (args.length > subIndex + 1 ? Boolean.parseBoolean(args[subIndex + 1]) ? 64 : itemStack.getMaxStackSize() : itemStack.getMaxStackSize())); } break; case "set": int slot = Integer.parseInt(args[subIndex + 1]); inventory.setItem( slot >= inventory.getSize() ? inventory.getSize() - 1 : slot, LogiBlocksMain.parseItemStack(args[subIndex + 2])); break; case "copy": Inventory targetInventory; if (args[subIndex + 1].startsWith("@l[") && args[subIndex + 1].endsWith("]")) { Block targetBlock = LogiBlocksMain.parseLocation(args[subIndex + 1], location).getBlock(); if (targetBlock.getState() instanceof InventoryHolder) { targetInventory = ((InventoryHolder) targetBlock.getState()).getInventory(); } else { return false; } } else { Player player = Bukkit.getPlayer(args[subIndex + 1]); if (player == null) { return false; } targetInventory = player.getInventory(); } for (int i = 0; i < inventory.getSize() && i < targetInventory.getSize(); i++) { targetInventory.setItem(i, inventory.getItem(i)); } break; case "show": Player player = Bukkit.getPlayer(args[subIndex + 1]); if (player == null) { return false; } if (args.length > subIndex + 2) { if (Boolean.parseBoolean(args[subIndex + 2])) { Inventory fakeInventory = Bukkit.createInventory(inventory.getHolder(), inventory.getType()); fakeInventory.setContents(inventory.getContents()); player.openInventory(fakeInventory); return true; } } else { player.openInventory(inventory); } break; } } return true; }
public void expandItems(final User user, final List<String> items) throws Exception { try { IText input = new SimpleTextInput(items); IText output = new KeywordReplacer(input, user.getSource(), ess); boolean spew = false; final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); for (String kitItem : output.getLines()) { if (kitItem.startsWith(ess.getSettings().getCurrencySymbol())) { BigDecimal value = new BigDecimal( kitItem.substring(ess.getSettings().getCurrencySymbol().length()).trim()); Trade t = new Trade(value, ess); t.pay(user, OverflowType.DROP); continue; } if (kitItem.startsWith("/")) { String command = kitItem.substring(1); String name = user.getName(); command = command.replace("{player}", name); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); continue; } final String[] parts = kitItem.split(" +"); final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1); if (parseStack.getType() == Material.AIR) { continue; } final MetaItemStack metaStack = new MetaItemStack(parseStack); if (parts.length > 2) { // We pass a null sender here because kits should not do perm checks metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess); } final Map<Integer, ItemStack> overfilled; final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks"); if (allowOversizedStacks) { overfilled = InventoryWorkaround.addOversizedItems( user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack()); } else { overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack()); } for (ItemStack itemStack : overfilled.values()) { int spillAmount = itemStack.getAmount(); if (!allowOversizedStacks) { itemStack.setAmount( spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize()); } while (spillAmount > 0) { user.getWorld().dropItemNaturally(user.getLocation(), itemStack); spillAmount -= itemStack.getAmount(); } spew = true; } } user.getBase().updateInventory(); if (spew) { user.sendMessage(tl("kitInvFull")); } } catch (Exception e) { user.getBase().updateInventory(); ess.getLogger().log(Level.WARNING, e.getMessage()); throw new Exception(tl("kitError2"), e); } }
@SuppressWarnings("deprecation") public Interface_Buy_Sell_Item( final List<InventoryInterface> link_Back_Stack, Player player, Shop shop_, final ItemStack itemStack_to_be_bought, final int amount, boolean deleteable, final boolean item_is_bought_without_shop) { super(Message_Handler.resolve_to_message(63), 4, link_Back_Stack); this.shop = shop_; this.setCloseable(false); this.amount = amount; this.deleteable = deleteable; this.itemStack_to_be_bought = itemStack_to_be_bought; try { this.permissionToBUY = "PrimeShop.Defaults.buyfromShop." + shop.shopname; this.permissionToSELL = "PrimeShop.Defaults.sellfromShop." + shop.shopname; } catch (Exception e) { if (!item_is_bought_without_shop) e.printStackTrace(); this.permissionToBUY = "PrimeShop.VIP.canBuySellAllItemsRegardlessIfTheyWereAddedToAShop"; this.permissionToSELL = "PrimeShop.VIP.canBuySellAllItemsRegardlessIfTheyWereAddedToAShop"; } this.setClickHandler( new ClickHandler() { @Override public boolean onClick( Player player, ItemStack cursor, ItemStack current, ClickType type) { // player.sendMessage("Du hast gedrückt"); return false; } }); // Empty Option for (int a = 0; a < this.getWidth(); a++) { for (int b = 0; b < this.getHeight(); b++) { this.addOption( a, b, new Button_with_no_task(Cofiguration_Handler.background_ItemStack, " ")); } } // Kaufen Button_Buy_Sell_Item buy_Button = new Button_Buy_Sell_Item(permissionToBUY, true, 55, itemStack_to_be_bought, ""); this.addOption(3, 2, buy_Button); buy_Button.setDisplayIcon(Cofiguration_Handler.buyButton_ItemStack); buy_Button.refresh_price(this.amount); // Verkaufen Button_Buy_Sell_Item sell_Button = new Button_Buy_Sell_Item(permissionToSELL, false, this.amount, itemStack_to_be_bought, ""); this.addOption(5, 2, sell_Button); sell_Button.setDisplayIcon(Cofiguration_Handler.sellButton_ItemStack); sell_Button.refresh_price(this.amount); if (PrimeShop.has_player_Permission_for_this_Command(player, "PrimeShop.admin.changePrices")) { if (this.shop != null) { if (PrimeShop.get_all_SubItems_of_ItemStack(itemStack_to_be_bought).isEmpty() || PrimeShop.plugin.is_PriceLinking_disabled_for_Item(itemStack_to_be_bought)) { // Change Price ItemStack currentItem = new ItemStack(Material.getMaterial(266)); this.addOption( 8, 2, new Button( currentItem.getType(), currentItem.getData().getData(), Message_Handler.resolve_to_message(22), Message_Handler.resolve_to_message(125)) { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { PrimeShop.close_InventoyInterface(player); PrimeShop.databaseHandler.link_with_Databse_if_not_allready_linked( PrimeShop.get_Shop_Item_of_Itemstack(itemStack_to_be_bought)); PrimeShop.open_InventoyInterface( player, new Interface_Change_Price( inventoryInterface.branch_back_Stack, player, itemStack_to_be_bought.clone())); } }); // Changing Rate currentItem = new ItemStack(Material.getMaterial(66)); this.addOption( 8, 1, new Button( currentItem.getType(), currentItem.getData().getData(), Message_Handler.resolve_to_message(24), Message_Handler.resolve_to_message(124)) { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { if (Cofiguration_Handler.dynamic_pricing_for_all_Items_DISABLED) { player.sendMessage( ChatColor.RED + "Dynamic pricing is disabled in the config.yml!"); return; } PrimeShop.close_InventoyInterface(player); PrimeShop.databaseHandler.link_with_Databse_if_not_allready_linked( PrimeShop.get_Shop_Item_of_Itemstack(itemStack_to_be_bought)); PrimeShop.open_InventoyInterface( player, new Interface_Change_Rate( inventoryInterface.branch_back_Stack, player, itemStack_to_be_bought.clone())); } }); } else { // List all SubItems this.addOption( 8, 2, new Button( Material.getMaterial(14), (short) 1, Message_Handler.resolve_to_message(49), Message_Handler.resolve_to_message(50), Message_Handler.resolve_to_message(51)) { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { PrimeShop.close_InventoyInterface(player); PrimeShop.open_InventoyInterface( player, new Interface_List_of_Subitems( inventoryInterface.branch_back_Stack, itemStack_to_be_bought, shop, player)); } }); } // Enable PriceLinking if (PrimeShop.plugin.is_PriceLinking_disabled_for_Item(itemStack_to_be_bought)) { addOption( 7, 3, new Button( Material.ANVIL, Message_Handler.resolve_to_message(52), Message_Handler.resolve_to_message(53)) { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { if (PrimeShop.plugin.is_PriceLinking_disabled_for_Item(itemStack_to_be_bought)) { PrimeShop.plugin.enable_PriceLinking_for_Item(itemStack_to_be_bought); PrimeShop.close_InventoyInterface(player); PrimeShop.open_InventoyInterface( player, inventoryInterface.branch_back_Stack.get( inventoryInterface.position_in_Stack - 1)); } } }); } } if (shop_ != null) { if (PrimeShop.has_player_Permission_for_this_Command( player, "PrimeShop.admin.addItemsToShop." + shop_.shopname)) { // Remove Item from Shop if (deleteable) { this.addOption( 8, 3, new Button( Material.WOOL, (short) 14, Message_Handler.resolve_to_message(54), Message_Handler.resolve_to_message(55), "") { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { PrimeShop.close_InventoyInterface(player); PrimeShop.open_InventoyInterface( player, new Interface_delete_Item_from_Shop( inventoryInterface.branch_back_Stack, player, itemStack_to_be_bought, shop)); } }); } } } } // Display Icon if (itemStack_to_be_bought.getMaxStackSize() > 1) { Button_Amount button_Amount = new Button_Amount( itemStack_to_be_bought, "", Message_Handler.resolve_to_message(56), Message_Handler.resolve_to_message(57), Message_Handler.resolve_to_message(58), Message_Handler.resolve_to_message(59)); button_Amount.setAmount(this.amount); this.addOption(4, 0, button_Amount); } else { this.addOption( 4, 0, new Button_with_no_task( itemStack_to_be_bought, "", Message_Handler.resolve_to_message( 56, PrimeShop.convert_IemStack_to_DisplayName(itemStack_to_be_bought)), Message_Handler.resolve_to_message(60))); } // Close Option this.addOption(8, 0, new Button_close_Interface()); // Go Back Option if (!item_is_bought_without_shop) { if (position_in_Stack > 0) { this.addOption( 0, 0, new Button( shop.displayIcon, Message_Handler.resolve_to_message(61), Message_Handler.resolve_to_message(62)) { @Override public void onClick( InventoryInterface inventoryInterface, Player player, ItemStack cursor, ItemStack current, ClickType type) { PrimeShop.close_InventoyInterface(player); PrimeShop.open_InventoyInterface( player, inventoryInterface.branch_back_Stack.get(position_in_Stack - 1)); } }); } } }