Java Code Examples for org.bukkit.inventory.Inventory

The following examples show how to use org.bukkit.inventory.Inventory. These examples are extracted from open source projects. 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 Project: TradePlus   Source File: InvUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Inventory getTradeInventory(Player player1, Player player2) {
  Inventory inv =
      Bukkit.createInventory(
          player1.getInventory().getHolder(),
          54,
          ChatColor.translateAlternateColorCodes('&', pl.getConfig().getString("gui.title"))
              .replace("%PLAYER%", player2.getName()));
  for (int i = 4; i <= 49; i += 9) inv.setItem(i, placeHolder);
  if (pl.getConfig().getBoolean("gui.showaccept")) {
    inv.setItem(0, acceptTrade);
    inv.setItem(8, theyCancelled);
    if (pl.getConfig().getBoolean("gui.force.enabled", true)
        && player1.hasPermission("tradeplus.admin")) inv.setItem(49, force);
  } else {
    inv.setItem(0, placeHolder);
    inv.setItem(8, placeHolder);
  }
  if (pl.getConfig().getBoolean("gui.showhead", true))
    inv.setItem(
        4,
        ItemFactory.getPlayerSkull(
            player2,
            pl.getConfig().getString("gui.head").replace("%PLAYER%", player2.getName())));
  return inv;
}
 
Example 2
Source Project: ServerTutorial   Source File: Base64Serialize.java    License: MIT License 6 votes vote down vote up
public static String toBase64(Inventory inventory) {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);

        // Write the size of the inventory
        dataOutput.writeInt(inventory.getSize());

        // Save every element in the list
        for (int i = 0; i < inventory.getSize(); i++) {
            dataOutput.writeObject(inventory.getItem(i));
        }

        // Serialize that array
        dataOutput.close();
        return Base64Coder.encodeLines(outputStream.toByteArray());
    } catch (Exception e) {
        throw new IllegalStateException("Cannot into itemstacksz!", e);
    }
}
 
Example 3
Source Project: Shopkeepers   Source File: PlayerShopkeeper.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected int getCurrencyInChest() {
	int total = 0;
	Block chest = this.getChest();
	if (Utils.isChest(chest.getType())) {
		Inventory inv = ((Chest) chest.getState()).getInventory();
		ItemStack[] contents = inv.getContents();
		for (ItemStack item : contents) {
			if (Settings.isCurrencyItem(item)) {
				total += item.getAmount();
			} else if (Settings.isHighCurrencyItem(item)) {
				total += item.getAmount() * Settings.highCurrencyValue;
			}
		}
	}
	return total;
}
 
Example 4
Source Project: CardinalPGM   Source File: ObserverModule.java    License: MIT License 6 votes vote down vote up
public void refreshView(final UUID view) {
    if (Bukkit.getPlayer(view) != null && viewing.containsKey(view)) {
        List<UUID> viewers = viewing.get(view);
        for (int i = 0; i < viewers.size(); i++) {
            Player player = Bukkit.getPlayer(viewers.get(i));
            if (player != null && player.getOpenInventory().getTitle().contains(Bukkit.getPlayer(view).getName())) {
                Inventory fake = getFakeInventory(Bukkit.getPlayer(view), player.getLocale());
                for (int i2 = 0; i2 < 45; i2 ++) {
                    try {
                        player.getOpenInventory().setItem(i2, fake.getItem(i2));
                    } catch (NullPointerException e) {
                    }
                }
                if (!player.getOpenInventory().getTitle().equals(Bukkit.getPlayer(view).getDisplayName())){
                    player.openInventory(fake);
                    viewing.get(view).add(viewers.get(i));
                }
            }
        }
    }
}
 
Example 5
Source Project: SkyWarsReloaded   Source File: ChestManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void fillCrate(Inventory inventory, int max) {
 	if (inventory != null) {
 		inventory.clear();
         int added = 0;
         Collections.shuffle(randomLoc);

for (int chance: crateItemList.keySet()) {
	for (ItemStack item : crateItemList.get(chance)) {
		if (item != null && !item.getType().equals(Material.AIR)) {
			if (random.nextInt(100) + 1 <= chance) {
				inventory.setItem(randomLoc.get(added), item);
				added++;
				if (added >= inventory.getSize() - 1 || added >= max) {
					break;
				}
			}
		}
	}
}
 	}
 }
 
Example 6
Source Project: uSkyBlock   Source File: SkyBlockMenu.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Inventory displayLogGUI(final Player player) {
    List<String> lores = new ArrayList<>();
    String title = "\u00a79" + tr("Island Log");
    Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 9, title);
    ItemMeta meta4 = sign.getItemMeta();
    meta4.setDisplayName("\u00a79\u00a7l" + tr("Island Log"));
    addLore(lores, tr("\u00a7eClick here to return to\n\u00a7ethe main island screen."));
    meta4.setLore(lores);
    sign.setItemMeta(meta4);
    menu.addItem(new ItemStack[]{sign});
    lores.clear();
    ItemStack menuItem = new ItemStack(Material.WRITABLE_BOOK, 1);
    meta4 = menuItem.getItemMeta();
    meta4.setDisplayName(tr("\u00a7e\u00a7lIsland Log"));
    for (String log : plugin.getIslandInfo(player).getLog()) {
        lores.add(log);
    }
    meta4.setLore(lores);
    menuItem.setItemMeta(meta4);
    menu.setItem(8, menuItem);
    lores.clear();
    return menu;
}
 
Example 7
@Subscribe
public void onSpectateLeave(FlagSpectate.SpectateLeaveEvent event) {
	Player player = event.getPlayer().getBukkitPlayer();
	Inventory inventory = player.getInventory();
	
	for (ItemStack stack : inventory.getContents()) {
		if (stack == null) {
			continue;
		}
		
		MetadatableItemStack metadatable = new MetadatableItemStack(stack);
		if (!metadatable.hasItemMeta() || !metadatable.getItemMeta().hasLore() || !metadatable.hasMetadata(TRACKER_KEY)) {
			continue;
		}
		
		inventory.remove(stack);
	}
	
	player.updateInventory();
	tracking.remove(player);
}
 
Example 8
Source Project: civcraft   Source File: LoreMaterial.java    License: 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 Project: Slimefun4   Source File: MagicWorkbench.java    License: GNU General Public License v3.0 6 votes vote down vote up
private boolean isCraftable(Inventory inv, ItemStack[] recipe) {
    for (int j = 0; j < inv.getContents().length; j++) {
        if (!SlimefunUtils.isItemSimilar(inv.getContents()[j], recipe[j], true)) {
            if (SlimefunItem.getByItem(recipe[j]) instanceof SlimefunBackpack) {
                if (!SlimefunUtils.isItemSimilar(inv.getContents()[j], recipe[j], false)) {
                    return false;
                }
            }
            else {
                return false;
            }
        }
    }

    return true;
}
 
Example 10
Source Project: WildernessTp   Source File: TrueFalseGui.java    License: MIT License 6 votes vote down vote up
public static void openTrue(Player p) {
    ItemStack close = new ItemStack(Material.REDSTONE_BLOCK, 1);
    ItemMeta meta = close.getItemMeta();
    meta.setDisplayName("Close");
    ArrayList<String> lore = new ArrayList<String>();
    lore.add("Click to close the inventory and return to normal gameplay");
    meta.setLore(lore);
    close.setItemMeta(meta);
    Inventory Wildtp = Bukkit.createInventory(p, 9, "Hooks");
    p.openInventory(Wildtp);
    if(!Wild.getInstance().thirteen) {
        Wildtp.setItem(2, MainGui.makeItem(Material.valueOf("WOOL"), "True", Collections.singletonList("Click to to enable the value to true"), (byte) 5));
        Wildtp.setItem(5, MainGui.makeItem(Material.valueOf("WOOL"), "False", Collections.singletonList("Click to to disable the value to false"), (byte) 14));
    }else{
        Wildtp.setItem(2, MainGui.makeItem(Material.valueOf("GREEN_WOOL"), "True", Collections.singletonList("Click to to enable the value to true")));
        Wildtp.setItem(5, MainGui.makeItem(Material.valueOf("RED_WOOL"), "False", Collections.singletonList("Click to to disable the value to false")));
    }
    Wildtp.setItem(8, close);
}
 
Example 11
Source Project: TabooLib   Source File: ItemStacker.java    License: MIT License 6 votes vote down vote up
private static boolean check(ItemStack item, Inventory inventory, int i) {
    if (Items.isNull(inventory.getItem(i))) {
        // 如果物品数量过多
        if (item.getAmount() > item.getType().getMaxStackSize()) {
            ItemStack itemClone = item.clone();
            itemClone.setAmount(item.getType().getMaxStackSize());
            inventory.setItem(i, itemClone);
            item.setAmount(item.getAmount() - item.getType().getMaxStackSize());
        } else {
            inventory.setItem(i, item.clone());
            item.setAmount(0);
            return true;
        }
    }
    return false;
}
 
Example 12
@Override
protected void saveEditor(Inventory inventory, Player player) {
	final BookPlayerShopkeeper shopkeeper = this.getShopkeeper();
	for (int column = 0; column < 8; column++) {
		ItemStack item = inventory.getItem(column);
		if (!Utils.isEmpty(item) && item.getType() == Material.WRITTEN_BOOK) {
			String bookTitle = getTitleOfBook(item);
			if (bookTitle != null) {
				int price = this.getPriceFromColumn(inventory, column);
				if (price > 0) {
					shopkeeper.addOffer(bookTitle, price);
				} else {
					shopkeeper.removeOffer(bookTitle);
				}
			}
		}
	}
}
 
Example 13
Source Project: UHC   Source File: IconInventory.java    License: MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void on(InventoryClickEvent event) {
    final Inventory inventory = event.getInventory();
    if (!inventory.getTitle().equals(title)) return;

    event.setCancelled(true);

    final int slot = event.getRawSlot();

    if (slot < 0 || slot >= inventory.getSize() || slot >= icons.size()) return;

    // call event
    final IconStack icon = icons.get(slot);

    if (icon != null) {
        icon.onClick((Player) event.getWhoClicked());
    }
}
 
Example 14
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onInventoryMove(InventoryMoveItemEvent event) {
    if (!super.getPlugin().getConfig().getBoolean("shop.update-sign-when-inventory-moving", true)) {
        return;
    }

    final Inventory inventory = event.getDestination();
    final Location location = inventory.getLocation();

    if (location == null) {
        return;
    }

    // Delayed task. Event triggers when item is moved, not when it is received.
    final Shop shop = getShopRedstone(location, true);
    if (shop != null) {
        super.getPlugin().getSignUpdateWatcher().scheduleSignUpdate(shop);
    }
}
 
Example 15
Source Project: TabooLib   Source File: Items.java    License: MIT License 6 votes vote down vote up
public static boolean takeItem(Inventory inventory, Matcher matcher, int amount) {
    int takeAmount = amount;
    ItemStack[] contents = inventory.getContents();
    for (int i = 0; i < contents.length; i++) {
        ItemStack itemStack = contents[i];
        if (!isNull(itemStack) && matcher.match(itemStack)) {
            takeAmount -= itemStack.getAmount();
            if (takeAmount < 0) {
                itemStack.setAmount(itemStack.getAmount() - (takeAmount + itemStack.getAmount()));
                return true;
            } else {
                inventory.setItem(i, null);
                if (takeAmount == 0) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 16
Source Project: QuickShop-Reremake   Source File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the number of items that can be given to the inventory safely.
 *
 * @param inv  The inventory to count
 * @param item The item prototype. Material, durabiltiy and enchants must match for 'stackability'
 *             to occur.
 * @return The number of items that can be given to the inventory safely.
 */
public static int countSpace(@Nullable Inventory inv, @NotNull ItemStack item) {
    if (inv == null) {
        return 0;
    }
    int space = 0;

    int itemMaxStackSize = getItemMaxStackSize(item.getType());

    ItemStack[] contents = inv.getStorageContents();
    for (final ItemStack iStack : contents) {
        if (iStack == null || iStack.getType() == Material.AIR) {
            space += itemMaxStackSize;
        } else if (plugin.getItemMatcher().matches(item, iStack)) {
            space += iStack.getAmount() >= itemMaxStackSize ? 0 : itemMaxStackSize - iStack.getAmount();
        }
    }
    return space / item.getAmount();
}
 
Example 17
Source Project: WildernessTp   Source File: MainGui.java    License: MIT License 6 votes vote down vote up
public static void OpenGUI(Player p) {
    ItemStack Close = new ItemStack(Material.REDSTONE_BLOCK, 1);
    ItemMeta meta = Close.getItemMeta();
    meta.setDisplayName("Close");
    ArrayList<String> lore = new ArrayList<String>();
    lore.add("Click to close the inventory and return to normal gameplay");
    meta.setLore(lore);
    Close.setItemMeta(meta);
    Inventory Wildtp = Bukkit.createInventory(p, 18, "WildTp");
    putEdit(p);
    p.openInventory(Wildtp);
    p.sendMessage(ChatColor.RED+"Please make sure to use the redstone block to close early or you wont be able to chat");
    Wildtp.setItem(17, Close);
    Wildtp.setItem(2, makeItem(Material.valueOf(getMaterials().get("Book")), "Messages", Collections.singletonList("Click to set the messages")));
    Wildtp.setItem(4, makeItem(Material.PAPER, "Set", Arrays.asList("Click me to set the values for x and z ","along with cooldown and cost")));
    Wildtp.setItem(6, makeItem(Material.BOOK,"Add a potion or world", Collections.singletonList("Click to add a potion or world")));
    Wildtp.setItem(0, makeItem(Material.JUKEBOX, "Sounds", Collections.singletonList("Click me to set the sound")));
    Wildtp.setItem(8, makeItem(Material.TRIPWIRE_HOOK,"Hooks", Collections.singletonList("Click me to enable or disable a hook")));
}
 
Example 18
/**
 * Add an item to shops chest.
 *
 * @param item   The itemstack. The amount does not matter, just everything else
 * @param amount The amount to add to the shop.
 */
@Override
public void add(@NotNull ItemStack item, int amount) {
    if (this.unlimited) {
        return;
    }
    item = item.clone();
    int itemMaxStackSize = Util.getItemMaxStackSize(item.getType());
    Inventory inv = this.getInventory();
    int remains = amount;
    while (remains > 0) {
        int stackSize = Math.min(remains, itemMaxStackSize);
        item.setAmount(stackSize);
        Objects.requireNonNull(inv).addItem(item);
        remains -= stackSize;
    }
    this.setSignText();
}
 
Example 19
Source Project: BedwarsRel   Source File: Region.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Region(Location pos1, Location pos2, String name) {
  if (pos1 == null || pos2 == null) {
    return;
  }

  if (!pos1.getWorld().getName().equals(pos2.getWorld().getName())) {
    return;
  }

  this.world = pos1.getWorld();
  this.setMinMax(pos1, pos2);
  this.placedBlocks = new ArrayList<Block>();
  this.breakedBlocks = new ArrayList<Block>();
  this.breakedBlockTypes = new HashMap<Block, Integer>();
  this.breakedBlockData = new HashMap<Block, Byte>();
  this.breakedBlockFace = new HashMap<Block, BlockFace>();
  this.placedUnbreakableBlocks = new ArrayList<Block>();
  this.breakedBlockPower = new HashMap<Block, Boolean>();
  this.inventories = new ArrayList<Inventory>();
  this.removingEntities = new ArrayList<Entity>();

  this.name = name;
}
 
Example 20
Source Project: Crazy-Crates   Source File: CrazyCrates.java    License: MIT License 5 votes vote down vote up
/**
 * Load the crate preview of a crate.
 * @param crate The crate you wish to load the preview of.
 * @return An Inventory object of the preview.
 */
public Inventory loadPreview(Crate crate) {
    FileConfiguration file = crate.getFile();
    int slots = 9;
    for (int size = file.getConfigurationSection("Crate.Prizes").getKeys(false).size(); size > 9 && slots < crate.getMaxSlots(); size -= 9) {
        slots += 9;
    }
    Inventory inv = Bukkit.createInventory(null, slots, Methods.sanitizeColor(file.getString("Crate.Name")));
    for (String reward : file.getConfigurationSection("Crate.Prizes").getKeys(false)) {
        String id = file.getString("Crate.Prizes." + reward + ".DisplayItem", "Stone");
        String name = file.getString("Crate.Prizes." + reward + ".DisplayName", "");
        List<String> lore = file.getStringList("Crate.Prizes." + reward + ".Lore");
        HashMap<Enchantment, Integer> enchantments = new HashMap<>();
        String player = file.getString("Crate.Prizes." + reward + ".Player", "");
        boolean glowing = file.getBoolean("Crate.Prizes." + reward + ".Glowing");
        int amount = file.getInt("Crate.Prizes." + reward + ".DisplayAmount", 1);
        for (String enchantmentName : file.getStringList("Crate.Prizes." + reward + ".DisplayEnchantments")) {
            Enchantment enchantment = Methods.getEnchantment(enchantmentName.split(":")[0]);
            if (enchantment != null) {
                enchantments.put(enchantment, Integer.parseInt(enchantmentName.split(":")[1]));
            }
        }
        try {
            inv.setItem(inv.firstEmpty(), new ItemBuilder().setMaterial(id).setAmount(amount).setName(name).setLore(lore).setEnchantments(enchantments).setGlowing(glowing).setPlayer(player).build());
        } catch (Exception e) {
            inv.addItem(new ItemBuilder().setMaterial("RED_TERRACOTTA", "STAINED_CLAY:14").setName("&c&lERROR").setLore(Arrays.asList("&cThere is an error", "&cFor the reward: &c" + reward)).build());
        }
    }
    return inv;
}
 
Example 21
Source Project: civcraft   Source File: ReportChestsTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int countItem(Inventory inv, int id) {
	int total = 0;
	for (ItemStack stack : inv.all(ItemManager.getMaterial(id)).values()) {
		total += stack.getAmount();
	}
	
	return total;
}
 
Example 22
Source Project: GriefDefender   Source File: PlayerEventHandler.java    License: MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteractInventoryClick(InventoryClickEvent event) {
    final HumanEntity player = event.getWhoClicked();
    GDCauseStackManager.getInstance().pushCause(player);
    if (!GDFlags.INTERACT_INVENTORY_CLICK || event.getClickedInventory() == null || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUID())) {
        return;
    }

    GDTimings.PLAYER_INTERACT_INVENTORY_CLICK_EVENT.startTiming();
    final Location location = player.getLocation();
    final GDClaim claim = this.dataStore.getClaimAt(location);
    final ItemStack cursorItem = event.getCursor();
    final Inventory source = event.getInventory();
    final ItemStack target = event.getCurrentItem();

    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.INTERACT_INVENTORY_CLICK.getName(), target, player.getWorld().getUID())) {
        GDTimings.PLAYER_INTERACT_INVENTORY_CLICK_EVENT.stopTiming();
        return;
    }

    final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(player.getUniqueId());
    final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_INVENTORY_CLICK, source, target, user, TrustTypes.CONTAINER, true);
    if (result == Tristate.FALSE) {
        final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_INTERACT_ITEM,
                ImmutableMap.of(
                "player", claim.getOwnerDisplayName(),
                "item", ItemTypeRegistryModule.getInstance().getNMSKey(target)));
        GriefDefenderPlugin.sendClaimDenyMessage(claim, player, message);
        event.setCancelled(true);
    }
    GDTimings.PLAYER_INTERACT_INVENTORY_CLICK_EVENT.stopTiming();
}
 
Example 23
Source Project: TradePlus   Source File: Trade.java    License: GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onDrag(InventoryDragEvent event) {
  if (!(event.getWhoClicked() instanceof Player)) {
    return;
  }
  Player player = (Player) event.getWhoClicked();
  Inventory inv = event.getInventory();
  if (inv1.getViewers().contains(player) || inv2.getViewers().contains(player)) {
    if (accept1 && accept2) {
      event.setCancelled(true);
      return;
    }

    for (int slot : event.getInventorySlots()) {
      if (!InvUtils.leftSlots.contains(slot)) {
        event.setCancelled(true);
        return;
      }
    }
    if (event.getInventorySlots().size() > 0) {
      if (pl.getConfig().getBoolean("antiscam.preventchangeonaccept")
          && ((player.equals(player1) && accept1) || (player.equals(player2) && accept2))) {
        event.setCancelled(true);
        return;
      }
      Bukkit.getScheduler().runTaskLater(pl, this::updateInventories, 1L);
      click();
    }
  } else if (inv.equals(spectatorInv)) {
    event.setCancelled(true);
  }
}
 
Example 24
Source Project: HeavySpleef   Source File: FlagItemReward.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean isInventoryFull(Inventory inventory) {
	ItemStack[] content = inventory.getContents();
	
	for (ItemStack stack : content) {
		if (stack != null && stack.getType() != Material.AIR) {
			continue;
		}
		
		return false;
	}
	
	return true;
}
 
Example 25
/**
 * Checks if an {@link org.bukkit.inventory.Inventory} is empty.
 */
public static boolean isInventoryEmpty(Inventory inventory)
{
    for (ItemStack content : inventory.getContents()) {
        if (content != null) {
            return false;
        }
    }
    return true;
}
 
Example 26
@Override
protected boolean openWindow(Player player) {
	final NormalPlayerShopkeeper shopkeeper = this.getShopkeeper();
	Inventory inventory = Bukkit.createInventory(player, 27, Settings.editorTitle);

	// add offers:
	List<ItemCount> chestItems = shopkeeper.getItemsFromChest();
	int column = 0;
	for (ItemCount itemCount : chestItems) {
		ItemStack item = itemCount.getItem(); // this item is already a copy with amount 1
		int price = 0;
		PriceOffer offer = shopkeeper.getOffer(item);
		if (offer != null) {
			price = offer.getPrice();
			item.setAmount(offer.getItem().getAmount());
		}

		// add offer to inventory:
		inventory.setItem(column, item);
		this.setEditColumnCost(inventory, column, price);

		column++;
		if (column > 8) break;
	}

	// add the special buttons:
	this.setActionButtons(inventory);
	// show editing inventory:
	player.openInventory(inventory);
	return true;
}
 
Example 27
Source Project: Crazy-Crates   Source File: Cosmic.java    License: MIT License 5 votes vote down vote up
public static void openCosmic(Player player, Crate crate, KeyType keyType, boolean checkHand) {
    Inventory inv = Bukkit.createInventory(null, 27, Methods.sanitizeColor(crate.getFile().getString("Crate.CrateName") + " - Choose"));
    setChests(inv, crate);
    cc.addPlayerKeyType(player, keyType);
    checkHands.put(player, checkHand);
    player.openInventory(inv);
}
 
Example 28
Source Project: Crazy-Crates   Source File: CSGO.java    License: MIT License 5 votes vote down vote up
private static void moveItems(Inventory inv, Player player, Crate crate) {
    ArrayList<ItemStack> items = new ArrayList<>();
    for (int i = 9; i > 8 && i < 17; i++) {
        items.add(inv.getItem(i));
    }
    inv.setItem(9, crate.pickPrize(player).getDisplayItem());
    for (int i = 0; i < 8; i++) {
        inv.setItem(i + 10, items.get(i));
    }
}
 
Example 29
Source Project: Skript   Source File: ItemType.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Removes this type from the given inventory. Does not call updateInventory for players.
 * 
 * @param invi
 * @return Whether everything could be removed from the inventory
 */
public boolean removeFrom(Inventory invi) {
	ItemStack[] buf = getCopiedContents(invi);
	
	final boolean ok = removeFrom(Arrays.asList(buf));
	
	invi.setContents(buf);
	return ok;
}
 
Example 30
Source Project: Slimefun4   Source File: BackpackCrafter.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void upgradeBackpack(Player p, Inventory inv, SlimefunBackpack backpack, ItemStack output) {
    ItemStack backpackItem = null;

    for (int j = 0; j < 9; j++) {
        if (inv.getContents()[j] != null && inv.getContents()[j].getType() != Material.AIR && SlimefunItem.getByItem(inv.getContents()[j]) instanceof SlimefunBackpack) {
            backpackItem = inv.getContents()[j];
            break;
        }
    }

    int size = backpack.getSize();
    Optional<String> id = retrieveID(backpackItem, size);

    if (id.isPresent()) {
        for (int line = 0; line < output.getItemMeta().getLore().size(); line++) {
            if (output.getItemMeta().getLore().get(line).equals(ChatColors.color("&7ID: <ID>"))) {
                ItemMeta im = output.getItemMeta();
                List<String> lore = im.getLore();
                lore.set(line, lore.get(line).replace("<ID>", id.get()));
                im.setLore(lore);
                output.setItemMeta(im);
                break;
            }
        }
    }
    else {
        for (int line = 0; line < output.getItemMeta().getLore().size(); line++) {
            if (output.getItemMeta().getLore().get(line).equals(ChatColors.color("&7ID: <ID>"))) {
                int target = line;

                PlayerProfile.get(p, profile -> {
                    int backpackId = profile.createBackpack(size).getId();
                    SlimefunPlugin.getBackpackListener().setBackpackId(p, output, target, backpackId);
                });

                break;
            }
        }
    }
}