Java Code Examples for org.bukkit.inventory.PlayerInventory#addItem()

The following examples show how to use org.bukkit.inventory.PlayerInventory#addItem() . 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: ShopMenuItem.java    From AnnihilationPro with MIT License 9 votes vote down vote up
@Override
public void onItemClick(ItemClickEvent event)
{
	Player player = event.getPlayer();
	PlayerInventory p = player.getInventory();
	if(p.containsAtLeast(new ItemStack(Material.GOLD_INGOT), cost))
	{
		int total = 0;
		for(ItemStack s : p.all(Material.GOLD_INGOT).values())
		{
			total += s.getAmount();
		}
		p.remove(Material.GOLD_INGOT);
		if(total-cost > 0)
			p.addItem(new ItemStack(Material.GOLD_INGOT,total-cost));
		p.addItem(product);
		player.sendMessage(Lang.PURCHASEDITEM.toString());
	}
	else player.sendMessage(Lang.COULDNOTPURCHASE.toString());
}
 
Example 2
Source File: PlayerEvents.java    From uSkyBlock with GNU General Public License v3.0 7 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void onClickOnObsidian(final PlayerInteractEvent event) {
    if (!plugin.getWorldManager().isSkyWorld(event.getPlayer().getWorld())) {
        return;
    }
    long now = System.currentTimeMillis();
    Player player = event.getPlayer();
    PlayerInventory inventory = player.getInventory();
    Block block = event.getClickedBlock();
    Long lastClick = obsidianClick.get(player.getUniqueId());
    if (lastClick != null && (lastClick + OBSIDIAN_SPAM) >= now) {
        plugin.notifyPlayer(player, tr("\u00a74You can only convert obsidian once every 10 seconds"));
        return;
    }
    if (Settings.extras_obsidianToLava && plugin.playerIsOnIsland(player)
            && plugin.getWorldManager().isSkyWorld(player.getWorld())
            && event.getAction() == Action.RIGHT_CLICK_BLOCK
            && player.getItemInHand() != null
            && player.getItemInHand().getType() == Material.BUCKET
            && block != null
            && block.getType() == Material.OBSIDIAN
            && !testForObsidian(block)) {
        if (inventory.firstEmpty() != -1) {
            obsidianClick.put(player.getUniqueId(), now);
            player.sendMessage(tr("\u00a7eChanging your obsidian back into lava. Be careful!"));
            inventory.removeItem(new ItemStack(Material.BUCKET, 1));
            inventory.addItem(new ItemStack(Material.LAVA_BUCKET, 1));
            player.updateInventory();
            block.setType(Material.AIR);
            event.setCancelled(true); // Don't execute the click anymore (since that would re-place the lava).
        } else {
            player.sendMessage(tr("\u00a7eYour inventory must have another empty space!"));
        }
    }
}
 
Example 3
Source File: MiscUtils.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void giveItemsToPlayer(List<ItemStack> itemStackList, Player player, TeamColor teamColor) {
    for (ItemStack itemStack : itemStackList) {
        final String materialName = itemStack.getType().toString();
        final PlayerInventory playerInventory = player.getInventory();

        if (materialName.contains("HELMET")) {
            playerInventory.setHelmet(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("CHESTPLATE")) {
            playerInventory.setChestplate(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("LEGGINGS")) {
            playerInventory.setLeggings(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("BOOTS")) {
            playerInventory.setBoots(Main.applyColor(teamColor, itemStack));
        } else {
            playerInventory.addItem(Main.applyColor(teamColor, itemStack));
        }
    }
}
 
Example 4
Source File: MiscUtils.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void giveItemsToPlayer(List<ItemStack> itemStackList, Player player, TeamColor teamColor) {
    for (ItemStack itemStack : itemStackList) {
        final String materialName = itemStack.getType().toString();
        final PlayerInventory playerInventory = player.getInventory();

        if (materialName.contains("HELMET")) {
            playerInventory.setHelmet(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("CHESTPLATE")) {
            playerInventory.setChestplate(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("LEGGINGS")) {
            playerInventory.setLeggings(Main.applyColor(teamColor, itemStack));
        } else if (materialName.contains("BOOTS")) {
            playerInventory.setBoots(Main.applyColor(teamColor, itemStack));
        } else {
            playerInventory.addItem(Main.applyColor(teamColor, itemStack));
        }
    }
}
 
Example 5
Source File: Main.java    From ArmorStandTools with MIT License 6 votes vote down vote up
void restoreInventory(Player p) {
    removeAllTools(p);
    UUID uuid = p.getUniqueId();
    ItemStack[] savedInv = savedInventories.get(uuid);
    if(savedInv == null) return;
    PlayerInventory plrInv = p.getInventory();
    ItemStack[] newItems = plrInv.getContents().clone();
    plrInv.setContents(savedInv);
    savedInventories.remove(uuid);
    for(ItemStack i : newItems) {
        if(i == null) continue;
        HashMap<Integer, ItemStack> couldntFit = plrInv.addItem(i);
        for (ItemStack is : couldntFit.values()) {
            p.getWorld().dropItem(p.getLocation(), is);
        }
    }
    p.sendMessage(ChatColor.GREEN + Config.invReturned);
}
 
Example 6
Source File: ItemKeepMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public void restoreKeptInventory(MatchPlayer player) {
  Map<Integer, ItemStack> kept = this.keptInv.remove(player);
  if (kept != null) {
    List<ItemStack> displaced = new ArrayList<>();
    PlayerInventory inv = player.getBukkit().getInventory();

    for (Map.Entry<Integer, ItemStack> entry : kept.entrySet()) {
      int slot = entry.getKey();
      ItemStack keptStack = entry.getValue();
      ItemStack invStack = inv.getItem(slot);

      if (invStack == null) {
        inv.setItem(slot, keptStack);
      } else {
        if (invStack.isSimilar(keptStack)) {
          int n =
              Math.min(keptStack.getAmount(), invStack.getMaxStackSize() - invStack.getAmount());
          invStack.setAmount(invStack.getAmount() + n);
          keptStack.setAmount(keptStack.getAmount() - n);
        }
        if (keptStack.getAmount() > 0) {
          displaced.add(keptStack);
        }
      }
    }

    for (ItemStack stack : displaced) {
      inv.addItem(stack);
    }
  }
}
 
Example 7
Source File: AdditionsCmd.java    From AdditionsAPI with MIT License 5 votes vote down vote up
/**
 * @param player
 *            Can't be null
 * @param idName
 *            Can't be null
 * @param amount
 *            Can be null
 * @param durability
 *            Can be null - Uses the Vanilla Style durability adjustments.
 * @return
 */
public static boolean giveCommand(Player player, String idName, Integer amount, Integer durability, CommandSender sender) {
	if (player == null || idName == null)
		return false;

	PlayerInventory inv = player.getInventory();
	CustomItemStack cStack = new CustomItemStack(idName);

	if (amount != null && !amount.equals(1)) {
		sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "===--- Additions API by chrismin13 ---===");
		sender.sendMessage(ChatColor.GREEN + "             ---=== Give Command ===---");
		sender.sendMessage("");
		sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "No Custom Items can be stacked.");
		sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Any amount of over 1 will be denied.");
		return true;
	}

	if (durability != null)
		cStack.setFakeDurability(cStack.getMaxFakeDurability() - durability);

	inv.addItem(cStack.getItemStack());

	sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "===--- Additions API by chrismin13 ---===");
	sender.sendMessage(ChatColor.GREEN + "             ---=== Give Command ===---");
	sender.sendMessage("");
	sender.sendMessage("Gave Custom Item: " + ChatColor.BOLD + idName);
	sender.sendMessage(
			"Amount: " + ChatColor.BOLD + cStack.getCustomItem().getAmount() + ChatColor.RESET + " Durability: "
					+ ChatColor.BOLD + cStack.getFakeDurability() + " / " + cStack.getMaxFakeDurability());

	return true;
}
 
Example 8
Source File: BukkitPlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void giveItem(int type, int amt) {
    final PlayerInventory inv = player.getInventory();
    final ItemStack newItem = new ItemStack(type, amt);
    if (type == WorldEdit.getInstance().getConfiguration().wandItem) {
        inv.remove(newItem);
    }
    final ItemStack item = player.getItemInHand();
    player.setItemInHand(newItem);
    if (item != null) {
        HashMap<Integer, ItemStack> overflow = inv.addItem(item);
        if (overflow != null && !overflow.isEmpty()) {
            TaskManager.IMP.sync(new RunnableVal<Object>() {
                @Override
                public void run(Object value) {
                    for (Map.Entry<Integer, ItemStack> entry : overflow.entrySet()) {
                        ItemStack stack = entry.getValue();
                        if (stack.getType() != Material.AIR && stack.getAmount() > 0) {
                            Item dropped = player.getWorld().dropItem(player.getLocation(), stack);
                            PlayerDropItemEvent event = new PlayerDropItemEvent(player, dropped);
                            if (event.isCancelled()) {
                                dropped.remove();
                            }
                        }
                    }
                }
            });
        }
    }
    player.updateInventory();
}
 
Example 9
Source File: ClearInventoryAction.java    From UHC with MIT License 5 votes vote down vote up
@Override
protected void revert(Player player) {
    final PlayerInventory inv = player.getInventory();

    inv.setContents(contents);
    inv.setArmorContents(armourContents);
    player.setItemOnCursor(onCursor);

    if (crafting.isPresent()) {
        // add back to main inventory instead of the crafting slots
        inv.addItem(crafting.get());
    }
}
 
Example 10
Source File: PlayerStateHolder.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public void apply(Player player, boolean teleport) {
	PlayerInventory playerInv = player.getInventory();
	boolean is1_9 = MinecraftVersion.getImplementationVersion().compareTo(MinecraftVersion.V1_9) >= 0;
       boolean isSimpleSize = playerInv.getContents().length <= SIMPLE_INVENTORY_SIZE;

       ItemStack[] inventoryContents = new ItemStack[is1_9 && !isSimpleSize ? playerInv.getSize() : SIMPLE_INVENTORY_SIZE];
       System.arraycopy(inventory, 0, inventoryContents, 0, inventoryContents.length);

       if (!is1_9 || isSimpleSize) {
           ItemStack[] armorContents = new ItemStack[ARMOR_INVENTORY_SIZE];
           System.arraycopy(inventory, inventory.length - ARMOR_INVENTORY_SIZE, armorContents, 0, armorContents.length);
           playerInv.setArmorContents(armorContents);
       }
	
	playerInv.setContents(inventoryContents);

	player.setItemOnCursor(null);
	Map<Integer, ItemStack> exceeded = playerInv.addItem(onCursor);
	for (ItemStack stack : exceeded.values()) {
           if (stack.getType() == Material.AIR) {
               continue;
           }
           
		player.getWorld().dropItem(player.getLocation(), stack);
	}
	
	player.updateInventory();

       player.setMaxHealth(maxHealth);
	player.setHealth(health);
	player.setFoodLevel(foodLevel);
	player.setLevel(level);
	player.setExp(experience);
	player.setAllowFlight(allowFlight);
	player.setFlying(isFlying);
	
	/* Remove current potion effects */
	Collection<PotionEffect> effects = player.getActivePotionEffects();
	for (PotionEffect effect : effects) {
		player.removePotionEffect(effect.getType());
	}
	player.addPotionEffects(activeEffects);
	
	player.setExhaustion(exhaustion);
	player.setSaturation(saturation);
	player.setFallDistance(fallDistance);
	player.setFireTicks(fireTicks);
	
	if (scoreboard != player.getScoreboard()) {
		Scoreboard showBoard = scoreboard;
		if (scoreboard == null) {
			showBoard = Bukkit.getScoreboardManager().getMainScoreboard();
		}
		
		player.setScoreboard(showBoard);
	}
	
	if (teleport) {
		player.teleport(location);
	}
	
	Location compassTarget = this.compassTarget;
	
	if (compassTarget == null) {
		compassTarget = player.getWorld().getSpawnLocation();
	}
	
	player.setCompassTarget(compassTarget);
	
	for (WeakReference<Player> ref : cantSee) {
		Player cantSeePlayer = ref.get();
		
		if (cantSeePlayer == null) {
			// Player object has been garbage-collected
			continue;
		}
		
		if (!cantSeePlayer.isOnline()) {
			continue;
		}
		
		player.hidePlayer(cantSeePlayer);
	}
	
	player.setGameMode(gamemode);
}