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

The following examples show how to use org.bukkit.inventory.Inventory#getSize() . 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: InventoryTypeAdapter.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
public static Inventory fromBase64(String data) {
    try {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
        BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
        Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());

        // Read the serialized inventory
        for (int i = 0; i < inventory.getSize(); i++) {
            inventory.setItem(i, (ItemStack) dataInput.readObject());
        }
        dataInput.close();
        return inventory;
    } catch (Exception e) {
    }
    return null;
}
 
Example 2
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 3
Source File: PickerMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Open the window for the given player, or refresh its contents if they already have it open, and
 * return the current contents.
 *
 * <p>If the window is currently open but too small to hold the current contents, it will be
 * closed and reopened.
 *
 * <p>If the player is not currently allowed to have the window open, close any window they have
 * open and return null.
 */
private @Nullable Inventory showWindow(MatchPlayer player) {
  if (!checkWindow(player)) return null;

  ItemStack[] contents = createWindowContents(player);
  Inventory inv = getOpenWindow(player);
  if (inv != null && inv.getSize() < contents.length) {
    inv = null;
    closeWindow(player);
  }
  if (inv == null) {
    inv = openWindow(player, contents);
  } else {
    inv.setContents(contents);
  }
  return inv;
}
 
Example 4
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 5
Source File: Base64Serialization.java    From PlayerVaults with GNU General Public License v3.0 6 votes vote down vote up
public static Inventory fromBase64(String data, String target) {
    try {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
        BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
        Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());
        // Read the serialized inventory
        for (int i = 0; i < inventory.getSize(); i++) {
            inventory.setItem(i, (ItemStack) dataInput.readObject());
        }
        dataInput.close();
        PlayerVaults.debug("Read " + inventory.getSize() + " items");
        return inventory;
    } catch (Exception e) {
        PlayerVaults.getInstance().getLogger().log(Level.SEVERE, "Failed to load vault " + target, e);
    }
    return null;
}
 
Example 6
Source File: Base64Serialize.java    From ServerTutorial with MIT License 6 votes vote down vote up
public static Inventory fromBase64(String data) {
    try {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
        BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
        Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());

        // Read the serialized inventory
        for (int i = 0; i < inventory.getSize(); i++) {
            inventory.setItem(i, (ItemStack) dataInput.readObject());
        }
        dataInput.close();
        return inventory;
    } catch (Exception e) {
    }
    return null;
}
 
Example 7
Source File: InventoryGui.java    From InventoryGui with MIT License 6 votes vote down vote up
/**
 * Draw the elements in the inventory. This can be used to manually refresh the gui.
 * @param who For who to draw the GUI
 */
public void draw(HumanEntity who) {
    Inventory inventory = getInventory(who);
    if (inventory == null) {
        build();
        if (slots.length != inventoryType.getDefaultSize()) {
            inventory = plugin.getServer().createInventory(new Holder(this), slots.length, replaceVars(title));
        } else {
            inventory = plugin.getServer().createInventory(new Holder(this), inventoryType, replaceVars(title));
        }
        inventories.put(who != null ? who.getUniqueId() : null, inventory);
    } else {
        inventory.clear();
    }
    for (int i = 0; i < inventory.getSize(); i++) {
        GuiElement element = getElement(i);
        if (element == null) {
            element = getFiller();
        }
        if (element != null) {
            inventory.setItem(i, element.getItem(who, i));
        }
    }
}
 
Example 8
Source File: QuestItemHandler.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onRespawn(final PlayerRespawnEvent event) {
    if (Config.getString("config.remove_items_after_respawn").equals("false"))
        return;
    // some plugins block item dropping after death and add those
    // items after respawning, so the player doesn't loose his
    // inventory after death; this aims to force removing quest
    // items, as they have been added to the backpack already
    if (event.getPlayer().getGameMode() == GameMode.CREATIVE)
        return;
    final Inventory inv = event.getPlayer().getInventory();
    for (int i = 0; i < inv.getSize(); i++) {
        if (Utils.isQuestItem(inv.getItem(i))) {
            inv.setItem(i, null);
        }
    }
}
 
Example 9
Source File: FlagLeaveItem.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@Subscribe(priority = Subscribe.Priority.LOW)
public void onGameStart(GameStartEvent event) {
	for (SpleefPlayer player : event.getGame().getPlayers()) {
		Player bukkitPlayer = player.getBukkitPlayer();
		Inventory inv = bukkitPlayer.getInventory();
		
		for (int i = 0; i < inv.getSize(); i++) {
			ItemStack stack = inv.getItem(i);
			if (stack == null || stack.getType() == Material.AIR) {
				continue;
			}
			
			MetadatableItemStack metadatable = new MetadatableItemStack(stack);
			if (!metadatable.hasItemMeta() || !metadatable.getItemMeta().hasLore() || !metadatable.hasMetadata(LEAVE_ITEM_KEY)) {
				continue;
			}
			
			inv.setItem(i, null);
		}
		
		bukkitPlayer.updateInventory();
	}
}
 
Example 10
Source File: Journal.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Removes journal from player's inventory.
 *
 * @return the slot from which the journal was removed
 */
public int removeFromInv() {
    // loop all items and check if any of them is a journal
    Inventory inventory = PlayerConverter.getPlayer(playerID).getInventory();
    for (int i = 0; i < inventory.getSize(); i++) {
        if (isJournal(playerID, inventory.getItem(i))) {
            inventory.setItem(i, new ItemStack(Material.AIR));
            return i;
        }
    }
    return -1;
}
 
Example 11
Source File: LoveAtFirstSightListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
private boolean addPlayerToTeam(UhcPlayer player, UhcTeam team){
    if (team.isFull()) return false;
    Inventory teamInventory = team.getTeamInventory();

    for (ItemStack item : player.getTeam().getTeamInventory().getContents()){
        if (item == null || item.getType() == Material.AIR){
            continue;
        }

        if (teamInventory.getContents().length < teamInventory.getSize()){
            teamInventory.addItem(item);
        }else {
            try {
                Player bukkitPlayer = player.getPlayer();
                bukkitPlayer.getWorld().dropItem(bukkitPlayer.getLocation(), item);
            }catch (UhcPlayerNotOnlineException ex){
                ex.printStackTrace();
            }
        }
    }

    player.setTeam(team);
    team.getMembers().add(player);

    team.sendMessage(Lang.TEAM_MESSAGE_PLAYER_JOINS.replace("%player%", player.getName()));
    GameManager gm = GameManager.getGameManager();
    gm.getScoreboardManager().updatePlayerTab(player);
    if (!disableBroadcasts){
        gm.broadcastMessage(Lang.SCENARIO_LOVEATFIRSTSIGHT_JOIN_BROADCAST.replace("%player%", player.getName()).replace("%leader%", team.getLeader().getName()));
    }
    return true;
}
 
Example 12
Source File: TrMenuNmsOld.java    From TrMenu with MIT License 5 votes vote down vote up
@Override
public void setInventoryTitle(Player player, Inventory inventory, String title) {
    EntityPlayer handle = ((CraftPlayer) player).getHandle();
    PacketPlayOutOpenWindow packet = new PacketPlayOutOpenWindow(
            handle.activeContainer.windowId,
            getByInventory(inventory),
            new ChatComponentText(title),
            inventory.getSize()
    );
    handle.playerConnection.sendPacket(packet);
    handle.updateInventory(handle.activeContainer);
}
 
Example 13
Source File: CrateControl.java    From Crazy-Crates with MIT License 5 votes vote down vote up
@EventHandler
public void onAdminMenuClick(InventoryClickEvent e) {
    Inventory inv = e.getInventory();
    Player player = (Player) e.getWhoClicked();
    if (inv != null && e.getView().getTitle().equals(Methods.sanitizeColor("&4&lAdmin Keys"))) {
        e.setCancelled(true);
        if (!Methods.permCheck(player, "admin")) {
            player.closeInventory();
            return;
        }
        //Added the >= due to an error about a raw slot set at -999.
        if (e.getRawSlot() < inv.getSize() && e.getRawSlot() >= 0) {//Clicked in the admin menu.
            ItemStack item = inv.getItem(e.getRawSlot());
            if (cc.isKey(item)) {
                Crate crate = cc.getCrateFromKey(item);
                if (e.getAction() == InventoryAction.PICKUP_ALL) {
                    player.getInventory().addItem(crate.getKey());
                } else if (e.getAction() == InventoryAction.PICKUP_HALF) {
                    cc.addKeys(1, player, crate, KeyType.VIRTUAL_KEY);
                    String name = null;
                    ItemStack key = crate.getKey();
                    if (key.hasItemMeta() && key.getItemMeta().hasDisplayName()) {
                        name = key.getItemMeta().getDisplayName();
                    }
                    player.sendMessage(Methods.getPrefix() + Methods.color("&a&l+1 " + (name != null ? name : crate.getName())));
                }
            }
        }
    }
}
 
Example 14
Source File: InventoryMenu.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Open the window for the given player, or refresh its contents if they already have it open, and
 * return the current contents.
 *
 * <p>If the window is currently open but too small to hold the current contents, it will be
 * closed and reopened.
 *
 * <p>If the player is not currently allowed to have the window open, close any window they have
 * open and return null.
 */
private @Nullable Inventory showWindow(MatchPlayer player) {
  ItemStack[] contents = createWindowContents(player);
  Inventory inv = getOpenWindow(player);
  if (inv != null && inv.getSize() < contents.length) {
    inv = null;
    closeWindow(player);
  }
  if (inv == null) {
    inv = openWindow(player, contents);
  } else {
    inv.setContents(contents);
  }
  return inv;
}
 
Example 15
Source File: Tools.java    From ce with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Inventory getItemMenu(Player p) {
    if (!p.isOp() && !p.hasPermission("ce.item.*")) {
        Inventory lInv = Main.CEItemMenu;
        Inventory items = Bukkit.createInventory(null, lInv.getSize(), lInv.getTitle());
        items.setContents(lInv.getContents());
        for (int i = 0; i < items.getSize() - 2; i++) {
            ItemStack item = items.getItem(i);
            if (item == null || item.getType().equals(Material.AIR))
                continue;
            ItemMeta im = item.getItemMeta();
            List<String> lore = new ArrayList<String>();
            if (im.hasLore())
                lore = im.getLore();
            for (CItem ci : Main.items)
                if (item.getItemMeta().getDisplayName().equals(ci.getDisplayName())) {
                    if (!checkPermission(ci, p)) {
                        lore.add(ChatColor.RED + "You are not permitted to use this");
                        break;
                    }
                }
            im.setLore(lore);
            item.setItemMeta(im);
        }
        return items;
    }

    return Main.CEItemMenu;
}
 
Example 16
Source File: QMenuCancel.java    From Quests with MIT License 5 votes vote down vote up
public Inventory toInventory() {
    String title = Options.color(Options.GUITITLE_QUEST_CANCEL.getStringValue());

    ItemStack yes = Items.QUEST_CANCEL_YES.getItem();
    ItemStack no = Items.QUEST_CANCEL_NO.getItem();

    ItemStack background = Items.QUEST_CANCEL_BACKGROUND.getItem();
    ItemMeta backgroundMeta = background.getItemMeta();
    backgroundMeta.setDisplayName(" ");
    background.setItemMeta(backgroundMeta);

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

    for (int i = 0; i < inventory.getSize(); i++) {
        inventory.setItem(i, background);
    }

    inventory.setItem(10, no);
    inventory.setItem(11, no);
    inventory.setItem(12, no);
    inventory.setItem(13, quest.getDisplayItem().toItemStack(quest, owner.getQuestProgressFile(), owner.getQuestProgressFile().getQuestProgress(quest)));
    inventory.setItem(14, yes);
    inventory.setItem(15, yes);
    inventory.setItem(16, yes);

    return inventory;
}
 
Example 17
Source File: TrMenuNmsModern.java    From TrMenu with MIT License 4 votes vote down vote up
private Containers<?> getByInventory(Inventory inventory) {
    InventoryType type = inventory.getType();
    int size = inventory.getSize();
    if (type == InventoryType.CHEST) {
        if (size == 9) {
            return Containers.GENERIC_9X1;
        } else if (size == 18) {
            return Containers.GENERIC_9X2;
        } else if (size == 27) {
            return Containers.GENERIC_9X3;
        } else if (size == 36) {
            return Containers.GENERIC_9X4;
        } else if (size == 45) {
            return Containers.GENERIC_9X5;
        } else {
            return Containers.GENERIC_9X6;
        }
    } else if (type == InventoryType.DROPPER || type == InventoryType.DISPENSER) {
        return Containers.GENERIC_3X3;
    } else if (type == InventoryType.BARREL || type == InventoryType.ENDER_CHEST) {
        return Containers.GENERIC_9X3;
    } else if (type == InventoryType.CRAFTING || type == InventoryType.WORKBENCH) {
        return Containers.CRAFTING;
    } else if (type == InventoryType.HOPPER) {
        return Containers.HOPPER;
    } else if (type == InventoryType.LOOM) {
        return Containers.LOOM;
    } else if (type == InventoryType.ANVIL) {
        return Containers.ANVIL;
    } else if (type == InventoryType.BEACON) {
        return Containers.BEACON;
    } else if (type == InventoryType.SMOKER) {
        return Containers.SMOKER;
    } else if (type == InventoryType.BREWING) {
        return Containers.BREWING_STAND;
    } else if (type == InventoryType.FURNACE) {
        return Containers.FURNACE;
    } else if (type == InventoryType.LECTERN) {
        return Containers.LECTERN;
    } else if (type == InventoryType.MERCHANT) {
        return Containers.MERCHANT;
    } else if (type == InventoryType.ENCHANTING) {
        return Containers.ENCHANTMENT;
    } else if (type == InventoryType.GRINDSTONE) {
        return Containers.GRINDSTONE;
    } else if (type == InventoryType.CARTOGRAPHY) {
        return Containers.CARTOGRAPHY_TABLE;
    } else if (type == InventoryType.SHULKER_BOX) {
        return Containers.SHULKER_BOX;
    } else if (type == InventoryType.STONECUTTER) {
        return Containers.STONECUTTER;
    } else if (type == InventoryType.BLAST_FURNACE) {
        return Containers.BLAST_FURNACE;
    } else {
        return Containers.GENERIC_3X3;
    }
}
 
Example 18
Source File: GUI.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
private Window(@NotNull final Inventory inventory, @NotNull final GUI gui) {
	this.inventory = inventory;
	this.buttonMap = new Button[inventory.getSize()];
	this.gui = gui;
}
 
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: Trade.java    From TradePlus with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onClose(InventoryCloseEvent event) {
  Inventory closed = event.getInventory();
  if (closed == null || closed.getSize() < 54) {
    return;
  }

  // I keep having issues with
  // identifying inventories so
  // trying to make sure it catches
  // all events
  if (closed.equals(inv1)
      || closed.equals(inv2)
      || inv1.getViewers().contains(event.getPlayer())
      || inv2.getViewers().contains(event.getPlayer())) {
    if ((event.getPlayer().equals(player1) && !cancelOnClose1)
        || (event.getPlayer().equals(player2) && !cancelOnClose2)) {
      return;
    }

    giveOnCursor((Player)event.getPlayer());

    if (cancelled || closed.getItem(49) == null) {
      return;
    }

    cancel();

    pl.ongoingTrades.remove(this);
    if (task != null) {
      task.cancel();
      task = null;
    }

    player1.closeInventory();
    player2.closeInventory();

    // Return items to them
    giveItemsOnLeft(inv1, player1);
    giveItemsOnLeft(inv2, player2);

    MsgUtils.send(
        player1,
        pl.getLang()
            .getString("cancelled", "&4&l(!) &r&4The trade was cancelled")
            .replace("%PLAYER%", player2.getName()));
    MsgUtils.send(
        player2,
        pl.getLang()
            .getString("cancelled", "&4&l(!) &r&4The trade was cancelled")
            .replace("%PLAYER%", player1.getName()));
    new ArrayList<>(spectatorInv.getViewers()).forEach(HumanEntity::closeInventory);
  }
}