Java Code Examples for org.bukkit.inventory.Inventory#getItem()

The following examples show how to use org.bukkit.inventory.Inventory#getItem() . 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: WoolMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private void registerContainer(Inventory inv) {
  // When a chest (or other block inventory) is accessed, check if it's a wool chest
  Boolean isWoolChest = this.chests.get(inv);
  if (isWoolChest == null) {
    // If we haven't seen this chest yet, check it for wool
    isWoolChest = this.containsObjectiveWool(inv);
    this.chests.put(inv, isWoolChest);

    if (isWoolChest) {
      // If it is a wool chest, take a snapshot of the wools
      Map<Integer, ItemStack> contents = new HashMap<>();
      this.woolChests.put(inv, contents);
      for (int slot = 0; slot < inv.getSize(); ++slot) {
        ItemStack stack = inv.getItem(slot);
        if (stack != null && this.isObjectiveWool(stack)) {
          contents.put(slot, stack.clone());
        }
      }
    }
  }
}
 
Example 2
Source File: MainConfigMenu.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
private String findPath(Inventory inventory, int slot) {
    ItemStack item = inventory.getItem(slot);
    if (item == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(stripFormatting(item.getItemMeta().getDisplayName()));
    int row = slot / 9;
    int col = slot % 9;
    while (col >= 1) {
        ItemStack parent = inventory.getItem(getIndex(row, col));
        if(parent != null && parent.getType() != Material.PAPER) {
            col--;
            parent = inventory.getItem(getIndex(row, col));
        }
        else if(parent == null || parent.getType() != Material.PAPER) {
            row--;
            parent = inventory.getItem(getIndex(row, col));
        }
        else if (parent != null && parent.getType() == Material.PAPER) {
            sb.insert(0, stripFormatting(parent.getItemMeta().getDisplayName()) + ".");
            col--;
        }
    }
    return sb.toString();
}
 
Example 3
Source File: ItemKeep.java    From CardinalPGM with MIT License 6 votes vote down vote up
@EventHandler
public void onPlayerDeath(CardinalDeathEvent event) {
    Player player = event.getPlayer();
    Inventory inventory = player.getInventory();
    Map<Integer, ItemStack> itemsToKeep = new HashMap<>();
    if (inventory.getContents() != null) {
        for (int i = 0; i < inventory.getSize(); i++) {
            if (inventory.getItem(i) != null) {
                ItemStack item = inventory.getItem(i);
                if (item.getType().equals(type) && item.getDurability() == damageValue) {
                    itemsToKeep.put(i, item);
                    inventory.clear(i);
                }
            }
        }
    }
    items.put(player, itemsToKeep);
}
 
Example 4
Source File: WoolMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Repeatable(interval = @Time(seconds = 30), scope = MatchScope.RUNNING)
public void refillOneWoolPerContainer() {
    if(!Config.Wool.autoRefillWoolChests()) return;

    for(Entry<Inventory, Map<Integer, ItemStack>> chest : this.woolChests.entrySet()) {
        Inventory inv = chest.getKey();
        for(Entry<Integer, ItemStack> slotEntry : chest.getValue().entrySet()) {
            int slot = slotEntry.getKey();
            ItemStack wool = slotEntry.getValue();
            ItemStack stack = inv.getItem(slotEntry.getKey());

            if(stack == null) {
                stack = wool.clone();
                stack.setAmount(1);
                inv.setItem(slot, stack);
                break;
            } else if(stack.isSimilar(wool) && stack.getAmount() < wool.getAmount()) {
                stack.setAmount(stack.getAmount() + 1);
                inv.setItem(slot, stack);
                break;
            }
        }
    }
}
 
Example 5
Source File: WoolMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private void registerContainer(Inventory inv) {
    // When a chest (or other block inventory) is accessed, check if it's a wool chest
    Boolean isWoolChest = this.chests.get(inv);
    if(isWoolChest == null) {
        // If we haven't seen this chest yet, check it for wool
        isWoolChest = this.containsObjectiveWool(inv);
        this.chests.put(inv, isWoolChest);

        if(isWoolChest) {
            // If it is a wool chest, take a snapshot of the wools
            Map<Integer, ItemStack> contents = new HashMap<>();
            this.woolChests.put(inv, contents);
            for(int slot = 0; slot < inv.getSize(); ++slot) {
                ItemStack stack = inv.getItem(slot);
                if(stack != null && this.isObjectiveWool(stack)) {
                    contents.put(slot, stack.clone());
                }
            }
        }
    }
}
 
Example 6
Source File: ItemStacker.java    From TabooLib with MIT License 6 votes vote down vote up
/**
 * 合并物品,不新增
 */
public static AddResult addItemAndMerge(ItemStack item, Inventory inventory, Integer[] ignore) {
    boolean changed = false;
    int count = item.getAmount();
    int size = inventory instanceof PlayerInventory || inventory instanceof CraftingInventory ? 36 : inventory.getSize();
    for (int i = 0; i < size; i++) {
        if (ArrayUtil.contains(ignore, i)) {
            continue;
        }
        ItemStack inventoryItem = inventory.getItem(i);
        if (!item.isSimilar(inventoryItem)) {
            continue;
        }
        while (count > 0 && inventoryItem.getAmount() < item.getType().getMaxStackSize()) {
            changed = true;
            inventoryItem.setAmount(inventoryItem.getAmount() + 1);
            count--;
        }
        if (count == 0) {
            return new AddResult(count, changed);
        }
    }
    return new AddResult(count, changed);
}
 
Example 7
Source File: WoolMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private void refillOneWoolPerContainer() {
  if (!PGM.get().getConfiguration().shouldRefillWool()) return;

  for (Entry<Inventory, Map<Integer, ItemStack>> chest : this.woolChests.entrySet()) {
    Inventory inv = chest.getKey();
    for (Entry<Integer, ItemStack> slotEntry : chest.getValue().entrySet()) {
      int slot = slotEntry.getKey();
      ItemStack wool = slotEntry.getValue();
      ItemStack stack = inv.getItem(slotEntry.getKey());

      if (stack == null) {
        stack = wool.clone();
        stack.setAmount(1);
        inv.setItem(slot, stack);
        break;
      } else if (stack.isSimilar(wool) && stack.getAmount() < wool.getAmount()) {
        stack.setAmount(stack.getAmount() + 1);
        inv.setItem(slot, stack);
        break;
      }
    }
  }
}
 
Example 8
Source File: LoreMaterial.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void moveDropSet(Player player, Inventory inv, int slot, ItemStack newItem) {
	
	ItemStack stack = inv.getItem(slot);
	inv.setItem(slot, newItem);

	if (stack != null) {
		if (stack.equals(newItem)) {
			return;
		}
		
		HashMap<Integer, ItemStack> leftovers = inv.addItem(stack);
		
		for (ItemStack s : leftovers.values()) {
			player.getWorld().dropItem(player.getLocation(), s);
		}
	}
	
}
 
Example 9
Source File: ChestGUIUtils.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a item allowing to return to a previous gui
 *
 * @param guiInventory gui
 */
public static void addBackItem(GUIInventory guiInventory) {
	Inventory inventory = guiInventory.getInventory();
	NovaPlayer nPlayer = guiInventory.getViewer();

	ItemStack lastItem = inventory.getItem(inventory.getSize() - 1);
	if((lastItem == null || lastItem.getType() == Material.AIR) && nPlayer.getGuiInventoryHistory().size() > 1) {
		inventory.setItem(inventory.getSize() - 1, Message.INVENTORY_GUI_BACK.getItemStack());
	}
}
 
Example 10
Source File: Menu.java    From TrMenu with MIT License 5 votes vote down vote up
/**
 * 清理槽位变动导致的物品残留
 *
 * @param player 玩家
 * @param menu   容器
 */
public void clearEmptySlots(Player player, Inventory menu) {
    for (int i = 0; i < menu.getSize(); i++) {
        if (menu.getItem(i) != null && getButton(player, i) == null) {
            menu.setItem(i, null);
        }
    }
}
 
Example 11
Source File: CommandTemplate.java    From TrMenu with MIT License 5 votes vote down vote up
private TemplateMenu inventoryAsTrMenu(Inventory inventory) {
    HashMap<ItemStack, List<Integer>> items = new HashMap<>();

    for (int i = 0; i < inventory.getSize(); i++) {
        ItemStack item = inventory.getItem(i);
        if (Items.isNull(item)) {
            continue;
        }
        items.putIfAbsent(item, new ArrayList<>());
        items.get(item).add(i);
    }

    return new TemplateMenu("TrMenu Template", inventory.getSize() / 9, items);
}
 
Example 12
Source File: ExtendedIconMenu.java    From ChestCommands with GNU General Public License v3.0 5 votes vote down vote up
public void refresh(Player player, Inventory inventory) {
	try {
		for (int i = 0; i < icons.length; i++) {
			if (icons[i] != null && icons[i] instanceof ExtendedIcon) {
				ExtendedIcon extIcon = (ExtendedIcon) icons[i];

				if (extIcon.hasViewPermission() || extIcon.hasVariables()) {
					// Then we have to refresh it
					if (extIcon.canViewIcon(player)) {

						if (inventory.getItem(i) == null) {
							ItemStack newItem = ItemUtils.hideAttributes(extIcon.createItemstack(player));
							inventory.setItem(i, newItem);
						} else {
							// Performance, only update name and lore
							ItemStack oldItem = ItemUtils.hideAttributes(inventory.getItem(i));
							ItemMeta meta = oldItem.getItemMeta();
							meta.setDisplayName(extIcon.calculateName(player));
							meta.setLore(extIcon.calculateLore(player));
							oldItem.setItemMeta(meta);
						}

					} else {
						inventory.setItem(i, null);
					}
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		player.sendMessage(ChatColor.RED + "An internal error occurred while refreshing the menu. The staff should check the console for errors.");
	}
}
 
Example 13
Source File: IntegerEditMenu.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onClick(InventoryClickEvent event) {
    if (!(event.getInventory().getHolder() instanceof UltimateHolder) ||
            ((UltimateHolder) event.getInventory().getHolder()).getTitle() == null ||
            !stripFormatting(((UltimateHolder) event.getInventory().getHolder()).getTitle()).contains(stripFormatting(getTitle()))) {
        return false;
    }
    if (event.getSlotType() != InventoryType.SlotType.CONTAINER) {
        return true;
    }
    Player player = (Player) event.getWhoClicked();
    Inventory menu = event.getInventory();
    ItemStack returnItem = menu.getItem(getIndex(5, 0));
    String configName = returnItem.getItemMeta().getLore().get(0);
    String path = returnItem.getItemMeta().getLore().get(1);
    int page = getPage(returnItem.getItemMeta().getLore().get(2));
    int slot = event.getSlot();
    int row = slot / 9;
    int col = slot % 9;
    ItemStack clickedItem = event.getCurrentItem();
    if (slot >= getIndex(3, 0) && slot <= getIndex(3, 8)) {
        // increment buttons
        YmlConfiguration config = FileUtil.getYmlConfiguration(configName);
        int value = config.getInt(path, 0);
        int increment = getDisplayNameAsInt(clickedItem);
        if (event.getClick() == ClickType.LEFT) {
            value += increment;
        } else if (event.getClick() == ClickType.RIGHT) {
            value = increment;
        }
        config.set(path, value);
        config.set("dirty", true);
    }
    if (slot != getIndex(5,0)) {
        player.openInventory(createEditMenu(configName, path, page));
    } else {
        player.openInventory(parent.createEditMenu(configName, path, page));
    }
    return true;
}
 
Example 14
Source File: ItemUtils.java    From AdditionsAPI with MIT License 5 votes vote down vote up
/**
 * remove all itemstack thats similar to given itemstack.<br>
 * returns the number of items removed.<br>
 */
public static int removeAll(Inventory inv, ItemStack item) {
	int count = 0;

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

	return count;
}
 
Example 15
Source File: Utils.java    From ArmorStandTools with MIT License 5 votes vote down vote up
static void cycleInventory(Player p) {
    Inventory i = p.getInventory();
    ItemStack temp;
    for (int n = 0; n < 9; n++) {
        temp = i.getItem(n);
        i.setItem(n, i.getItem(27 + n));
        i.setItem(27 + n, i.getItem(18 + n));
        i.setItem(18 + n, i.getItem(9 + n));
        i.setItem(9 + n, temp);
    }
    //noinspection deprecation
    p.updateInventory();
}
 
Example 16
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
protected int getPriceFromColumn(Inventory inventory, int column) {
	ItemStack lowCostItem = inventory.getItem(column + 18);
	ItemStack highCostItem = inventory.getItem(column + 9);
	int cost = 0;
	if (lowCostItem != null && lowCostItem.getType() == Settings.currencyItem && lowCostItem.getAmount() > 0) {
		cost += lowCostItem.getAmount();
	}
	if (Settings.highCurrencyItem != Material.AIR && highCostItem != null && highCostItem.getType() == Settings.highCurrencyItem && highCostItem.getAmount() > 0) {
		cost += highCostItem.getAmount() * Settings.highCurrencyValue;
	}
	return cost;
}
 
Example 17
Source File: Tools.java    From ce with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Inventory getEnchantmentMenu(Player p, String name) {
    if (!p.isOp() && !p.hasPermission("ce.ench.*")) {
        Inventory lInv = getNextInventory(name);
        Inventory enchantments = Bukkit.createInventory(null, lInv.getSize(), lInv.getTitle());
        enchantments.setContents(lInv.getContents());
        for (int i = 0; i < enchantments.getSize() - 2; i++) {
            ItemStack checkItem = enchantments.getItem(i);
            if (checkItem == null || checkItem.getType().equals(Material.AIR))
                continue;
            ItemStack item = enchantments.getItem(i);
            ItemMeta im = item.getItemMeta();
            List<String> lore = new ArrayList<String>();
            if (im.hasLore())
                lore = im.getLore();
            for (CEnchantment ce : EnchantManager.getEnchantments()) {
                if (im.getDisplayName().equals(ce.getDisplayName()))
                    if (!checkPermission(ce, p)) {
                        lore.add(ChatColor.RED + "You are not permitted to use this");
                        break;
                    }
            }
            im.setLore(lore);
            item.setItemMeta(im);
            enchantments.setItem(i, item);
        }
        return enchantments;
    }

    return getNextInventory(name);
}
 
Example 18
Source File: LWC.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Deposit items into an inventory chest Works with double chests.
 *
 * @param block
 * @param itemStack
 * @return remaining items (if any)
 */
@SuppressWarnings("deprecation")
public Map<Integer, ItemStack> depositItems(Block block, ItemStack itemStack) {
    BlockState blockState;

    if ((blockState = block.getState()) != null && (blockState instanceof InventoryHolder)) {
        Block doubleChestBlock = null;
        InventoryHolder holder = (InventoryHolder) blockState;

        if (DoubleChestMatcher.PROTECTABLES_CHESTS.contains(block.getType())) {
            doubleChestBlock = findAdjacentDoubleChest(block);
        } else if (block.getType() == Material.FURNACE) {
            Inventory inventory = holder.getInventory();

            if (inventory.getItem(0) != null && inventory.getItem(1) != null) {
                if (inventory.getItem(0).getType() == itemStack.getType()
                        && inventory.getItem(0).getData().getData() == itemStack.getData().getData()
                        && inventory.getItem(0)
                        .getMaxStackSize() >= (inventory.getItem(0).getAmount() + itemStack.getAmount())) {
                    // ItemStack fits on Slot 0
                } else if (inventory.getItem(1).getType() == itemStack.getType()
                        && inventory.getItem(1).getData().getData() == itemStack.getData().getData()
                        && inventory.getItem(1)
                        .getMaxStackSize() >= (inventory.getItem(1).getAmount() + itemStack.getAmount())) {
                    // ItemStack fits on Slot 1
                } else {
                    return null;
                }
            }
        }

        if (itemStack.getAmount() <= 0) {
            return new HashMap<Integer, ItemStack>();
        }

        Map<Integer, ItemStack> remaining = holder.getInventory().addItem(itemStack);

        // we have remainders, deal with it
        if (remaining.size() > 0) {
            int key = remaining.keySet().iterator().next();
            ItemStack remainingItemStack = remaining.get(key);

            // is it a double chest ?????
            if (doubleChestBlock != null) {
                InventoryHolder holder2 = (InventoryHolder) doubleChestBlock.getState();
                remaining = holder2.getInventory().addItem(remainingItemStack);
            }

            // recheck remaining in the event of double chest being used
            if (remaining.size() > 0) {
                return remaining;
            }
        }
    }

    return new HashMap<Integer, ItemStack>();
}
 
Example 19
Source File: QMenuCategory.java    From Quests with MIT License 4 votes vote down vote up
public Inventory toInventory(int page) {
    int pageMin = pageSize * (page - 1);
    int pageMax = pageSize * page;
    String title = Options.color(Options.GUITITLE_QUESTS_CATEGORY.getStringValue());

    ItemStack pageIs = new ItemStack(Material.DIRT);

    Inventory inventory = Bukkit.createInventory(null, 54, title);

    for (int pointer = pageMin; pointer < pageMax; pointer++) {
        if (slotsToMenuQuest.containsKey(pointer)) {
            Category category = Quests.get().getQuestManager().getCategoryById(slotsToMenuQuest.get(pointer).getCategoryName());
            if (category != null) {
                inventory.setItem(pointer, category.getDisplayItem());
            }
        }
    }

    inventory.setItem(49, pageIs);

    if (Options.TRIM_GUI_SIZE.getBooleanValue() && page == 1) {
        int slotsUsed = 0;
        for (int pointer = 0; pointer < pageMax; pointer++) {
            if (inventory.getItem(pointer) != null) {
                slotsUsed++;
            }
        }

        int inventorySize = (slotsUsed >= 54) ? 54 : slotsUsed + (9 - slotsUsed % 9) * Math.min(1, slotsUsed % 9);
        inventorySize = inventorySize <= 0 ? 9 : inventorySize;
        if (inventorySize == 54) {
            return inventory;
        }

        Inventory trimmedInventory = Bukkit.createInventory(null, inventorySize, title);

        for (int slot = 0; slot < pageMax; slot++) {
            if (slot >= trimmedInventory.getSize()){
                break;
            }
            trimmedInventory.setItem(slot, inventory.getItem(slot));
        }
        return trimmedInventory;
    } else {
        return inventory;
    }

}
 
Example 20
Source File: Cosmic.java    From Crazy-Crates with MIT License 4 votes vote down vote up
@EventHandler
public void onInvClose(InventoryCloseEvent e) {
    Inventory inv = e.getInventory();
    Player player = (Player) e.getPlayer();
    Crate crate = cc.getOpeningCrate(player);
    if (cc.isInOpeningList(player)) {
        if (crate.getFile() == null) {
            return;
        } else {
            if (!crate.getFile().getString("Crate.CrateType").equalsIgnoreCase("Cosmic")) {
                return;
            }
        }
    } else {
        return;
    }
    if (e.getView().getTitle().equals(Methods.sanitizeColor(crate.getFile().getString("Crate.CrateName") + " - Prizes"))) {
        boolean playSound = false;
        for (int i : picks.get(player)) {
            if (inv.getItem(i) != null) {
                Tier tier = getTier(crate, inv.getItem(i));
                if (tier != null) {
                    Prize prize = crate.pickPrize(player, tier);
                    for (int stop = 0; prize == null && stop <= 2000; stop++) {
                        prize = crate.pickPrize(player, tier);
                    }
                    cc.givePrize(player, prize);
                    playSound = true;
                }
            }
        }
        if (playSound) {
            player.playSound(player.getLocation(), cc.getSound("UI_BUTTON_CLICK", "CLICK"), 1, 1);
        }
        cc.removePlayerFromOpeningList(player);
        cc.removePlayerKeyType(player);
        if (glass.containsKey(player)) {
            picks.put(player, glass.get(player));
            glass.remove(player);
        }
        checkHands.remove(player);
    }
    if (cc.isInOpeningList(player) && e.getView().getTitle().equals(Methods.sanitizeColor(crate.getFile().getString("Crate.CrateName") + " - Choose"))) {
        if (!glass.containsKey(player) || glass.get(player).size() < 4) {
            cc.removePlayerFromOpeningList(player);
            cc.removePlayerKeyType(player);
        }
        if (glass.containsKey(player)) {
            picks.put(player, glass.get(player));
            glass.remove(player);
        }
        checkHands.remove(player);
    }
}