org.bukkit.inventory.Inventory Java Examples

The following examples show how to use org.bukkit.inventory.Inventory. 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: IconInventory.java    From UHC with 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 #2
Source File: Region.java    From BedwarsRel with 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 #3
Source File: Base64Serialize.java    From ServerTutorial with 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 #4
Source File: InvUtils.java    From TradePlus with 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 #5
Source File: PlayerShopkeeper.java    From Shopkeepers with 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 #6
Source File: ObserverModule.java    From CardinalPGM with 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 #7
Source File: ChestManager.java    From SkyWarsReloaded with 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 #8
Source File: BookPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@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 #9
Source File: ContainerShop.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #10
Source File: SkyBlockMenu.java    From uSkyBlock with 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 #11
Source File: TrueFalseGui.java    From WildernessTp with 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 #12
Source File: MainGui.java    From WildernessTp with 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 #13
Source File: MagicWorkbench.java    From Slimefun4 with 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 #14
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 #15
Source File: BlockListener.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
@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 #16
Source File: FlagTrackingSpectate.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@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 #17
Source File: Items.java    From TabooLib with 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 #18
Source File: Util.java    From QuickShop-Reremake with 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 #19
Source File: ItemStacker.java    From TabooLib with 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 #20
Source File: FillListener.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) {
    final MatchPlayer opener = playerFinder.getParticipant(event.getActor());
    if(opener == null) return;

    final Inventory inventory = event.getInventory();
    final Predicate<Filter> passesFilter = passesFilter(inventory.getHolder());
    if(passesFilter == null) return;

    logger.fine(() -> opener.getName() + " opened a " + inventory.getHolder().getClass().getSimpleName());

    // Find all Fillers that apply to the holder of the opened inventory
    final List<Filler> fillers = this.fillers.stream()
                                             .filter(filler -> passesFilter.test(filler.filter()))
                                             .collect(Collectors.toImmutableList());
    if(fillers.isEmpty()) return;

    logger.fine(() -> "Found fillers " + fillers.stream()
                                                .map(Filler::identify)
                                                .collect(java.util.stream.Collectors.joining(", ")));

    // Find all Caches that the opened inventory is part of
    final List<Fillable> fillables = new ArrayList<>();
    for(Cache cache : caches) {
        if(passesFilter.test(cache.region()) && passesFilter.test(cache.filter())) {
            fillables.add(new FillableCache(cache));
        }
    }
    // If the inventory is not in any Cache, just fill it directly
    if(fillables.isEmpty()) {
        fillables.add(new FillableInventory(inventory));
    }

    fillables.forEach(fillable -> fillable.fill(opener, fillers));
}
 
Example #21
Source File: GUI.java    From Crazy-Auctions with MIT License 5 votes vote down vote up
public static void openBidding(Player player, String ID) {
    Methods.updateAuction();
    FileConfiguration config = Files.CONFIG.getFile();
    FileConfiguration data = Files.DATA.getFile();
    if (!data.contains("Items." + ID)) {
        openShop(player, ShopType.BID, shopCategory.get(player), 1);
        player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage());
        return;
    }
    Inventory inv = Bukkit.createInventory(null, 27, Methods.color(config.getString("Settings.Bidding-On-Item")));
    if (!bidding.containsKey(player)) bidding.put(player, 0);
    if (Version.getCurrentVersion().isNewer(Version.v1_12_R1)) {
        inv.setItem(9, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+1"));
        inv.setItem(10, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+10"));
        inv.setItem(11, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+100"));
        inv.setItem(12, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+1000"));
        inv.setItem(14, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-1000"));
        inv.setItem(15, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-100"));
        inv.setItem(16, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-10"));
        inv.setItem(17, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-1"));
    } else {
        inv.setItem(9, Methods.makeItem("160:5", 1, "&a+1"));
        inv.setItem(10, Methods.makeItem("160:5", 1, "&a+10"));
        inv.setItem(11, Methods.makeItem("160:5", 1, "&a+100"));
        inv.setItem(12, Methods.makeItem("160:5", 1, "&a+1000"));
        inv.setItem(14, Methods.makeItem("160:14", 1, "&c-1000"));
        inv.setItem(15, Methods.makeItem("160:14", 1, "&c-100"));
        inv.setItem(16, Methods.makeItem("160:14", 1, "&c-10"));
        inv.setItem(17, Methods.makeItem("160:14", 1, "&c-1"));
    }
    inv.setItem(13, getBiddingGlass(player, ID));
    inv.setItem(22, Methods.makeItem(config.getString("Settings.GUISettings.OtherSettings.Bid.Item"), 1, config.getString("Settings.GUISettings.OtherSettings.Bid.Name"), config.getStringList("Settings.GUISettings.OtherSettings.Bid.Lore")));
    
    inv.setItem(4, getBiddingItem(player, ID));
    player.openInventory(inv);
}
 
Example #22
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 #23
Source File: Talisman.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
private static void activateTalisman(Event e, Player p, Inventory inv, Talisman talisman, ItemStack talismanItem) {
    consumeItem(inv, talisman, talismanItem);
    applyTalismanEffects(p, talisman);
    cancelEvent(e, talisman);
    sendMessage(p, talisman);

}
 
Example #24
Source File: BookPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
private List<ItemStack> getBooksFromChest() {
	List<ItemStack> list = new ArrayList<ItemStack>();
	Block chest = this.getChest();
	if (Utils.isChest(chest.getType())) {
		Inventory inv = ((Chest) chest.getState()).getInventory();
		for (ItemStack item : inv.getContents()) {
			if (!Utils.isEmpty(item) && item.getType() == Material.WRITTEN_BOOK && this.isBookAuthoredByShopOwner(item)) {
				list.add(item);
			}
		}
	}
	return list;
}
 
Example #25
Source File: AdminCommand.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public void spawnunit_cmd() throws CivException {		
		if (args.length < 2) {
			throw new CivException("Enter a unit id.");
		}
		
		ConfigUnit unit = CivSettings.units.get(args[1]);
		if (unit == null) {
			throw new CivException("No unit called "+args[1]);
		}
		
		Player player = getPlayer();
		Town town = getNamedTown(2);
		
//		if (args.length > 2) {
//			try {
//				player = CivGlobal.getPlayer(args[2]);
//			} catch (CivException e) {
//				throw new CivException("Player "+args[2]+" is not online.");
//			}
//		} else {
//			player = getPlayer();
//		}
		
		Class<?> c;
		try {
			c = Class.forName(unit.class_name);
			Method m = c.getMethod("spawn", Inventory.class, Town.class);
			m.invoke(null, player.getInventory(), town);
		} catch (ClassNotFoundException | NoSuchMethodException | SecurityException 
				| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new CivException(e.getMessage());
		}

		
		CivMessage.sendSuccess(sender, "Spawned a "+unit.name);
	}
 
Example #26
Source File: InvUtils.java    From TradePlus with GNU General Public License v3.0 5 votes vote down vote up
public static Inventory getSpectatorInventory(Player player1, Player player2) {
  String title =
      ChatColor.translateAlternateColorCodes(
          '&', pl.getConfig().getString("gui.spectator-title"));
  if (Sounds.version > 1.8)
    title = title.replace("%PLAYER1%", player1.getName()).replace("%PLAYER2%", player2.getName());
  Inventory inv = Bukkit.createInventory(player1.getInventory().getHolder(), 54, title);
  for (int i = 4; i <= 49; i += 9) inv.setItem(i, placeHolder);
  for (int i = 45; i <= 53; i++) inv.setItem(i, placeHolder);
  inv.setItem(0, ItemFactory.getPlayerSkull(player1, "&f" + player1.getName()));
  inv.setItem(8, ItemFactory.getPlayerSkull(player2, "&f" + player2.getName()));
  inv.setItem(4, theyCancelled);
  return inv;
}
 
Example #27
Source File: CompatibilityUtils.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets clicked inventory
 * For API older than 1.8
 *
 * @param event inventory click event
 * @return inventory
 */
public static Inventory getClickedInventory(InventoryClickEvent event) {
	int slot = event.getRawSlot();
	InventoryView view = event.getView();

	if(slot < 0) {
		return null;
	}
	else if(view.getTopInventory() != null && slot < view.getTopInventory().getSize()) {
		return view.getTopInventory();
	}
	else {
		return view.getBottomInventory();
	}
}
 
Example #28
Source File: BackpackCrafter.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
protected Inventory createVirtualInventory(Inventory inv) {
    Inventory fakeInv = Bukkit.createInventory(null, 9, "Fake Inventory");

    for (int j = 0; j < inv.getContents().length; j++) {
        ItemStack stack = inv.getContents()[j] != null && inv.getContents()[j].getAmount() > 1 ? new CustomItem(inv.getContents()[j], inv.getContents()[j].getAmount() - 1) : null;
        fakeInv.setItem(j, stack);
    }

    return fakeInv;
}
 
Example #29
Source File: BackpackCrafter.java    From Slimefun4 with 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;
            }
        }
    }
}
 
Example #30
Source File: UnitMaterial.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public boolean hasFreeSlot(Inventory inv) {
	for (ItemStack stack : inv.getContents()) {
		if (stack == null) {
			return true;
		}
	}
	return false;
}