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

The following examples show how to use org.bukkit.inventory.Inventory#setContents() . 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: 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 2
Source File: IconInventory.java    From UHC with MIT License 6 votes vote down vote up
public void showTo(HumanEntity entity) {
    // how many icons do we want to show
    final int iconCount = icons.size();

    // how many slots are required, in increments of 9, min 9, max 54
    final int slotsRequired = Math.max(
            9,
            Math.min(
                    54,
                    INVENTORY_WIDTH * ((iconCount + INVENTORY_WIDTH - 1) / INVENTORY_WIDTH)
            )
    );

    // Create and render inventory
    final Inventory inventory = Bukkit.createInventory(null, slotsRequired, title);
    final ItemStack[] contents = new ItemStack[slotsRequired];
    for (int i = 0; i < icons.size(); i++) {
        contents[i] = icons.get(i);
    }

    inventory.setContents(contents);

    // Show to player
    entity.openInventory(inventory);
    openedInventories.add(inventory);
}
 
Example 3
Source File: Serialization.java    From PlayerVaults with GNU General Public License v3.0 6 votes vote down vote up
@Deprecated
public static Inventory toInventory(List<String> stringItems, int number, int size, String title) {
    VaultHolder holder = new VaultHolder(number);
    Inventory inv = Bukkit.createInventory(holder, size, title);
    holder.setInventory(inv);
    List<ItemStack> contents = new ArrayList<>();
    for (String piece : stringItems) {
        if (piece.equalsIgnoreCase("null")) {
            contents.add(null);
        } else {
            ItemStack item = (ItemStack) deserialize(toMap((JSONObject) JSONValue.parse(piece)));
            contents.add(item);
        }
    }
    ItemStack[] items = new ItemStack[contents.size()];
    for (int x = 0; x < contents.size(); x++) {
        items[x] = contents.get(x);
    }
    inv.setContents(items);
    return inv;
}
 
Example 4
Source File: PickerMatchModule.java    From ProjectAres 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.
 *
 * If the window is currently open but too small to hold the current
 * contents, it will be closed and reopened.
 *
 * 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 5
Source File: ViewInventoryMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public void previewInventory(Player viewer, Inventory realInventory) {
    if(viewer == null) { return; }

    if(realInventory instanceof PlayerInventory) {
        previewPlayerInventory(viewer, (PlayerInventory) realInventory);
    }else {
        Inventory fakeInventory;
        if(realInventory instanceof DoubleChestInventory) {
            if(realInventory.hasCustomName()) {
                fakeInventory = Bukkit.createInventory(viewer, realInventory.getSize(), realInventory.getName());
            } else {
                fakeInventory = Bukkit.createInventory(viewer, realInventory.getSize());
            }
        } else {
            if(realInventory.hasCustomName()) {
                fakeInventory = Bukkit.createInventory(viewer, realInventory.getType(), realInventory.getName());
            } else {
                fakeInventory = Bukkit.createInventory(viewer, realInventory.getType());
            }
        }
        fakeInventory.setContents(realInventory.contents());

        this.showInventoryPreview(viewer, realInventory, fakeInventory);
    }
}
 
Example 6
Source File: MultiInventory.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
private int removeItemFromInventory(Inventory inv, String mid, int type, short data, int amount) {
	int removed = 0;
	int notRemoved = amount;
	
	ItemStack[] contents = inv.getContents();
	for (int i = 0; i < contents.length; i++) {
		ItemStack stack = contents[i];
		if(!isCorrectItemStack(stack, mid, type, data)) {
			continue;
		}
		
		/* We've got the item we're looking for, lets remove as many as we can. */
		int stackAmount = stack.getAmount();
		
		if (stackAmount > notRemoved) {
			/* We've got more than enough in this stack. Reduce it's size. */
			stack.setAmount(stackAmount - notRemoved);
			removed = notRemoved;
			notRemoved = 0; /* We've got it all. */
		} else if (stackAmount == notRemoved) {
			/* Got the entire stack, null it out. */
			contents[i] = null;
			removed = notRemoved;
			notRemoved = 0;
		} else {
			/* There was some in this stack, but not enough for all we were looking for. */
			removed += stackAmount;
			notRemoved -= stackAmount;
			contents[i] = null;
		}
	
		if (notRemoved == 0) {
			/* We've removed everything. No need to continue. */
			break;
		}
	}
	
	inv.setContents(contents);
	return removed;
}
 
Example 7
Source File: VaultManager.java    From PlayerVaults with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get an inventory from file. Returns null if the inventory doesn't exist. SHOULD ONLY BE USED INTERNALLY
 *
 * @param playerFile the YamlConfiguration file.
 * @param size the size of the vault.
 * @param number the vault number.
 * @return inventory if exists, otherwise null.
 */
private Inventory getInventory(InventoryHolder owner, String ownerName, YamlConfiguration playerFile, int size, int number, String title) {
    Inventory inventory = Bukkit.createInventory(owner, size, title);

    String data = playerFile.getString(String.format(VAULTKEY, number));
    Inventory deserialized = Base64Serialization.fromBase64(data, ownerName);
    if (deserialized == null) {
        PlayerVaults.debug("Loaded vault as null");
        return inventory;
    }

    // Check if deserialized has more used slots than the limit here.
    // Happens on change of permission or if people used the broken version.
    // In this case, players will lose items.
    if (deserialized.getContents().length > size) {
        for (ItemStack stack : deserialized.getContents()) {
            if (stack != null) {
                inventory.addItem(stack);
            }
        }
    } else {
        inventory.setContents(deserialized.getContents());
    }

    PlayerVaults.debug("Loaded vault");
    return inventory;
}
 
Example 8
Source File: ItemFlagGui.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public void open() {
    //Register Listener
    RedProtect.get().getServer().getPluginManager().registerEvents(this, RedProtect.get());

    Inventory inv = Bukkit.createInventory(player, 54, "Item flag GUI");
    inv.setContents(this.guiItems);
    player.openInventory(inv);
}
 
Example 9
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 10
Source File: QueueManager.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void run(){
	HashMap<Block,ItemStack[]>openedChests = GameManager.openedChest.get(id);
	if( openedChests == null ) { SurvivalGames.debug("Nothing to reset for id "+id); return; }
	SurvivalGames.debug("Resetting saved chests content for game "+id);
	for( Block chest: openedChests.keySet() ) {
		BlockState bs = chest.getState();
		if(bs instanceof Chest || bs instanceof DoubleChest){
			SurvivalGames.debug("Resetting chest at "+chest.getX()+","+chest.getY()+","+chest.getZ()+" to previous contents");
			Inventory inv = ((bs instanceof Chest))? ((Chest) bs).getBlockInventory()
			: ((DoubleChest)bs).getLeftSide().getInventory(); // should handle double chests correctly!
			// replace current contents with saved contents
			try {
				inv.setContents(openedChests.get(chest));
				if(SettingsManager.getInstance().getConfig().getBoolean("debug", false)) {
					for( ItemStack is: inv.getContents() ) {
						if( is != null ) {
							SurvivalGames.debug("Restored item "+ is.getType().name() + " DV " + is.getDurability() + " qty "+is.getAmount());
						}
					}
				}
			} catch(Exception e) {
			    SurvivalGames.warning("Problem resetting chest at " +chest.getX()+","+chest.getY()+","+chest.getZ()+" to original state!");
			}
		} else {
			SurvivalGames.warning("Block in saved chests map is no longer a chest?");
		}
	}
	// forget saved content, so that randomisation can occur
	SurvivalGames.debug("Emptying list of opened chests for game "+id);
	GameManager.openedChest.put(id, new HashMap < Block, ItemStack[] > ());
}
 
Example 11
Source File: Recipes.java    From ProRecipes with GNU General Public License v2.0 5 votes vote down vote up
public void updateInventory(Player p, Inventory i){
	ItemStack[] contents = i.getContents();
	i.clear();
	//p.closeInventory();
	i.setContents(contents);
	//p.openInventory(i);
}
 
Example 12
Source File: InventoryMenu.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/** Open a new window for the given player displaying the given contents */
private Inventory openWindow(MatchPlayer player, ItemStack[] contents) {
  closeWindow(player);
  Inventory inv =
      Bukkit.createInventory(
          player.getBukkit(),
          getInventorySize(),
          StringUtils.truncate(getTranslatedTitle(player), 32));

  inv.setContents(contents);
  player.getBukkit().openInventory(inv);
  viewing.put(player, this);
  return inv;
}
 
Example 13
Source File: InventoryMenu.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * If the given player currently has the window open, refresh its contents and return the updated
 * inventory. The window will be closed and reopened if it is too small to hold the current
 * contents.
 *
 * <p>If the window is open but should be closed, close it and return null.
 *
 * <p>If the player does not have the window open, return null.
 */
public @Nullable Inventory refreshWindow(MatchPlayer player) {
  Inventory inv = getOpenWindow(player);
  if (inv != null) {
    ItemStack[] contents = createWindowContents(player);
    if (inv.getSize() < contents.length) {
      closeWindow(player);
      inv = openWindow(player, contents);
    } else {
      inv.setContents(contents);
    }
  }
  return inv;
}
 
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: ViewInventoryMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public void previewInventory(Player viewer, Inventory realInventory) {
  if (viewer == null) {
    return;
  }

  if (realInventory instanceof PlayerInventory) {
    previewPlayerInventory(viewer, (PlayerInventory) realInventory);
  } else {
    Inventory fakeInventory;
    if (realInventory instanceof DoubleChestInventory) {
      if (realInventory.hasCustomName()) {
        fakeInventory =
            Bukkit.createInventory(viewer, realInventory.getSize(), realInventory.getName());
      } else {
        fakeInventory = Bukkit.createInventory(viewer, realInventory.getSize());
      }
    } else {
      if (realInventory.hasCustomName()) {
        fakeInventory =
            Bukkit.createInventory(viewer, realInventory.getType(), realInventory.getName());
      } else {
        fakeInventory = Bukkit.createInventory(viewer, realInventory.getType());
      }
    }
    fakeInventory.setContents(realInventory.getContents());

    this.showInventoryPreview(viewer, realInventory, fakeInventory);
  }
}
 
Example 16
Source File: Listeners.java    From PlayerVaults with GNU General Public License v3.0 5 votes vote down vote up
public void saveVault(Player player, Inventory inventory) {
    if (plugin.getInVault().containsKey(player.getUniqueId().toString())) {

        Inventory inv = Bukkit.createInventory(null, 6 * 9);
        inv.setContents(inventory.getContents().clone());

        if (inventory.getViewers().size() == 1) {
            VaultViewInfo info = plugin.getInVault().get(player.getUniqueId().toString());
            vaultManager.saveVault(inv, info.getVaultName(), info.getNumber());
            plugin.getOpenInventories().remove(info.toString());
        }

        plugin.getInVault().remove(player.getUniqueId().toString());
    }
}
 
Example 17
Source File: Base64Serialization.java    From PlayerVaults with GNU General Public License v3.0 4 votes vote down vote up
public static String toBase64(ItemStack[] is, int size) {
    Inventory inventory = Bukkit.createInventory(null, size);
    inventory.setContents(is);
    return toBase64(inventory, size);
}
 
Example 18
Source File: NormalPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onPurchaseClick(InventoryClickEvent event, Player player, ItemStack[] usedRecipe, ItemStack offered1, ItemStack offered2) {
	super.onPurchaseClick(event, player, usedRecipe, offered1, offered2);
	if (event.isCancelled()) return;
	final NormalPlayerShopkeeper shopkeeper = this.getShopkeeper();

	// get offer for this type of item:
	ItemStack resultItem = usedRecipe[2];
	PriceOffer offer = shopkeeper.getOffer(resultItem);
	if (offer == null) {
		// this should not happen.. because the recipes were created based on the shopkeeper's offers
		event.setCancelled(true);
		return;
	}

	int tradedItemAmount = offer.getItem().getAmount();
	if (tradedItemAmount != resultItem.getAmount()) {
		// this shouldn't happen .. because the recipe was created based on this offer
		event.setCancelled(true);
		return;
	}

	// get chest:
	Block chest = shopkeeper.getChest();
	if (!Utils.isChest(chest.getType())) {
		event.setCancelled(true);
		return;
	}

	// remove result items from chest:
	Inventory inventory = ((Chest) chest.getState()).getInventory();
	ItemStack[] contents = inventory.getContents();
	contents = Arrays.copyOf(contents, contents.length);
	if (Utils.removeItems(contents, resultItem) != 0) {
		Log.debug("Chest does not contain the required items.");
		event.setCancelled(true);
		return;
	}

	// add earnings to chest:
	// TODO maybe add the actual items the trading player gave, instead of creating new currency items?
	int amount = this.getAmountAfterTaxes(offer.getPrice());
	if (amount > 0) {
		if (Settings.highCurrencyItem == Material.AIR || offer.getPrice() <= Settings.highCurrencyMinCost) {
			if (Utils.addItems(contents, Settings.createCurrencyItem(amount)) != 0) {
				Log.debug("Chest cannot hold the given items.");
				event.setCancelled(true);
				return;
			}
		} else {
			int highCost = amount / Settings.highCurrencyValue;
			int lowCost = amount % Settings.highCurrencyValue;
			if (highCost > 0) {
				if (Utils.addItems(contents, Settings.createHighCurrencyItem(highCost)) != 0) {
					Log.debug("Chest cannot hold the given items.");
					event.setCancelled(true);
					return;
				}
			}
			if (lowCost > 0) {
				if (Utils.addItems(contents, Settings.createCurrencyItem(lowCost)) != 0) {
					Log.debug("Chest cannot hold the given items.");
					event.setCancelled(true);
					return;
				}
			}
		}
	}

	// save chest contents:
	inventory.setContents(contents);
}
 
Example 19
Source File: BookPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onPurchaseClick(InventoryClickEvent event, Player player, ItemStack[] usedRecipe, ItemStack offered1, ItemStack offered2) {
	super.onPurchaseClick(event, player, usedRecipe, offered1, offered2);
	if (event.isCancelled()) return;
	final BookPlayerShopkeeper shopkeeper = this.getShopkeeper();

	ItemStack book = usedRecipe[2];
	String bookTitle = getTitleOfBook(book);
	if (bookTitle == null) {
		// this should not happen.. because the recipes were created based on the shopkeeper's offers
		event.setCancelled(true);
		return;
	}

	// get chest:
	Block chest = shopkeeper.getChest();
	if (!Utils.isChest(chest.getType())) {
		event.setCancelled(true);
		return;
	}

	// remove blank book from chest:
	boolean removed = false;
	Inventory inv = ((Chest) chest.getState()).getInventory();
	ItemStack[] contents = inv.getContents();
	for (int i = 0; i < contents.length; i++) {
		if (contents[i] != null && contents[i].getType() == Material.BOOK_AND_QUILL) {
			if (contents[i].getAmount() == 1) {
				contents[i] = null;
			} else {
				contents[i].setAmount(contents[i].getAmount() - 1);
			}
			removed = true;
			break;
		}
	}
	if (!removed) {
		event.setCancelled(true);
		return;
	}

	// get price:
	BookOffer offer = shopkeeper.getOffer(bookTitle);
	if (offer == null) {
		event.setCancelled(true);
		return;
	}
	int price = this.getAmountAfterTaxes(offer.getPrice());

	// add earnings to chest:
	if (price > 0) {
		int highCost = price / Settings.highCurrencyValue;
		int lowCost = price % Settings.highCurrencyValue;
		if (highCost > 0) {
			if (Utils.addItems(contents, Settings.createHighCurrencyItem(highCost)) != 0) {
				event.setCancelled(true);
				return;
			}
		}
		if (lowCost > 0) {
			if (Utils.addItems(contents, Settings.createCurrencyItem(lowCost)) != 0) {
				event.setCancelled(true);
				return;
			}
		}
	}

	// set chest contents:
	inv.setContents(contents);
}
 
Example 20
Source File: Base64Serialize.java    From ServerTutorial with MIT License 4 votes vote down vote up
public static String toBase64(ItemStack[] is, int size) {
    Inventory inventory = Bukkit.createInventory(null, size);
    inventory.setContents(is);
    return toBase64(inventory);
}