Java Code Examples for org.bukkit.entity.Player#getInventory()

The following examples show how to use org.bukkit.entity.Player#getInventory() . 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: Civilian.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
public int getCountNonStashItems(String name) {
    Player player = Bukkit.getPlayer(uuid);
    if (player == null) {
        return 0;
    }
    int count = 0;
    for (ItemStack is : player.getInventory()) {
        if (!CVItem.isCivsItem(is)) {
            continue;
        }
        CivItem civItem = CivItem.getFromItemStack(is);
        if (civItem == null) {
            continue;
        }
        if (!civItem.getProcessedName().equalsIgnoreCase(name) &&
                !civItem.getGroups().contains(name)) {
            continue;
        }
        count += is.getAmount();
    }

    count += getCountRegions(name);
    return count;
}
 
Example 4
Source File: GraphListener.java    From LagMonitor with MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onInteract(PlayerInteractEvent clickEvent) {
    Player player = clickEvent.getPlayer();
    PlayerInventory inventory = player.getInventory();

    ItemStack mainHandItem;
    if (mainHandSupported) {
        mainHandItem = inventory.getItemInMainHand();
    } else {
        mainHandItem = inventory.getItemInHand();
    }

    if (isOurGraph(mainHandItem)) {
        inventory.setItemInMainHand(new ItemStack(Material.AIR));
    }
}
 
Example 5
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 6
Source File: EntityDamage.java    From AdditionsAPI with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamage(EntityDamageEvent event) {
	if (event.isCancelled())
		return;

	DamageCause cause = event.getCause();
	Entity damagee = event.getEntity();
	EntityType damageeType = damagee.getType();
	// PlayerCustomArmorDamageEvent
	if (damageeType == EntityType.PLAYER) {
		Player player = (Player) damagee;
		PlayerInventory inv = player.getInventory();
		for (ItemStack armor : inv.getArmorContents())
			// TODO: Speed up
			if (armor != null && armor.getType() != Material.AIR && AdditionsAPI.isCustomItem(armor)
					&& new CustomItemStack(armor).getCustomItem() instanceof CustomArmor
					&& new CustomItemStack(armor).getCustomItem()
							.getDurabilityMechanics() instanceof ArmorDurability) {
				CustomArmor cArmor = (CustomArmor) new CustomItemStack(armor).getCustomItem();
				Bukkit.getServer().getPluginManager().callEvent(new PlayerCustomArmorDamageEvent(player, armor,
						cArmor, cause, (float) event.getDamage(), armor.containsEnchantment(Enchantment.THORNS)));
			}
	}
}
 
Example 7
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 8
Source File: ClearInventoryAction.java    From UHC with MIT License 6 votes vote down vote up
@Override
protected void run(Player player) {
    final PlayerInventory inv = player.getInventory();

    // clear main inventory
    contents = inv.getContents();
    inv.clear();

    // clear armour slots
    armourContents = inv.getArmorContents();
    inv.setArmorContents(null);

    // clear if they have something on their cursour currently
    onCursor = player.getItemOnCursor();
    player.setItemOnCursor(new ItemStack(Material.AIR));

    // if they have a crafting inventory open clear items from it too
    // stops storing items in crafting slots bypassing clear inventories
    final InventoryView openInventory = player.getOpenInventory();
    if (openInventory.getType() == InventoryType.CRAFTING) {
        crafting = Optional.of(openInventory.getTopInventory().getContents());
        openInventory.getTopInventory().clear();
    } else {
        crafting = Optional.absent();
    }
}
 
Example 9
Source File: Compat19.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent e) {
    Player p = e.getPlayer();

    // Glide options
    if (!p.hasPermission("redprotect.bypass.glide")) {
        if (!RedProtect.get().config.globalFlagsRoot().worlds.get(p.getWorld().getName()).player_glide.allow_elytra) {
            ItemStack item = p.getInventory().getChestplate();
            if (item != null && item.getType().equals(Material.ELYTRA)) {
                PlayerInventory inv = p.getInventory();
                inv.setChestplate(new ItemStack(Material.AIR));
                if (inv.firstEmpty() == -1) {
                    p.getWorld().dropItem(p.getLocation(), item);
                } else {
                    inv.setItem(inv.firstEmpty(), item);
                }
                p.playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP, 10, 1);
                RedProtect.get().lang.sendMessage(p, "globallistener.elytra.cantequip");
            }
        }
    }
}
 
Example 10
Source File: GraphListener.java    From LagMonitor with MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onInteract(PlayerInteractEvent clickEvent) {
    Player player = clickEvent.getPlayer();
    PlayerInventory inventory = player.getInventory();

    ItemStack mainHandItem;
    if (mainHandSupported) {
        mainHandItem = inventory.getItemInMainHand();
    } else {
        mainHandItem = inventory.getItemInHand();
    }

    if (isOurGraph(mainHandItem)) {
        inventory.setItemInMainHand(new ItemStack(Material.AIR));
    }
}
 
Example 11
Source File: KingsCrown.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPickup(EntityPickupItemEvent event) {
	Player player = ((Player) event.getEntity());
	PlayerInventory inv = player.getInventory();
	ItemStack lastHelmet = inv.getHelmet();
	if (lastHelmet == null || inv.addItem(lastHelmet).size() == 0) {
		inv.setHelmet(event.getItem().getItemStack());
		event.getItem().remove();
		event.setCancelled(true);
		if (shouldBroadcastMessage()) {
			UtilsMc.broadcastToWorld(player.getWorld(), MessageFormat.format("§6{0} §fhas been crown §6King§f!", player.getName(), getName()));
		}
	}
}
 
Example 12
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 13
Source File: ArmorKeep.java    From CardinalPGM with MIT License 5 votes vote down vote up
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    PlayerInventory inventory = player.getInventory();
    Map<Integer, ItemStack> itemsToKeep = new HashMap<>();
    if (inventory.getHelmet() != null) {
        if (inventory.getHelmet().getType().equals(type) && inventory.getHelmet().getDurability() == damageValue) {
            helmet.put(player, inventory.getHelmet());
            inventory.setHelmet(null);
        }
    }
    if (inventory.getChestplate() != null) {
        if (inventory.getChestplate().getType().equals(type) && inventory.getChestplate().getDurability() == damageValue) {
            chestplate.put(player, inventory.getChestplate());
            inventory.setChestplate(null);
        }
    }
    if (inventory.getLeggings() != null) {
        if (inventory.getLeggings().getType().equals(type) && inventory.getLeggings().getDurability() == damageValue) {
            leggings.put(player, inventory.getLeggings());
            inventory.setLeggings(null);
        }
    }
    if (inventory.getBoots() != null) {
        if (inventory.getBoots().getType().equals(type) && inventory.getBoots().getDurability() == damageValue) {
            boots.put(player, inventory.getBoots());
            inventory.setBoots(null);
        }
    }
}
 
Example 14
Source File: BrushListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerItemHoldEvent(final PlayerItemHeldEvent event) {
    final Player bukkitPlayer = event.getPlayer();
    if (bukkitPlayer.isSneaking()) {
        return;
    }
    FawePlayer<Object> fp = FawePlayer.wrap(bukkitPlayer);
    com.sk89q.worldedit.entity.Player player = fp.getPlayer();
    LocalSession session = fp.getSession();
    Tool tool = session.getTool(player);
    if (tool instanceof ScrollTool) {
        final int slot = event.getNewSlot();
        final int oldSlot = event.getPreviousSlot();
        final int ri;
        if ((((slot - oldSlot) <= 4) && ((slot - oldSlot) > 0)) || (((slot - oldSlot) < -4))) {
            ri = 1;
        } else {
            ri = -1;
        }
        ScrollTool scrollable = (ScrollTool) tool;
        if (scrollable.increment(player, ri)) {
            if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES) {
                bukkitPlayer.getInventory().setHeldItemSlot(oldSlot);
            } else {
                final PlayerInventory inv = bukkitPlayer.getInventory();
                final ItemStack item = inv.getItem(slot);
                final ItemStack newItem = inv.getItem(oldSlot);
                inv.setItem(slot, newItem);
                inv.setItem(oldSlot, item);
                bukkitPlayer.updateInventory();
            }
        }
    }
}
 
Example 15
Source File: FlagShovels.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void onGameStart(GameStartEvent event) {
	Game game = event.getGame();
	
	for (SpleefPlayer player : game.getPlayers()) {
		Player bukkitPlayer = player.getBukkitPlayer();
		Inventory inv = bukkitPlayer.getInventory();
		ItemStack stack = createShovel();
		
		inv.addItem(stack);
		
		bukkitPlayer.updateInventory();
	}
}
 
Example 16
Source File: MyCommand.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
public static PlayerInventory checkFullInventory(Player player) throws MyCommandException {
	PlayerInventory inv = player.getInventory();
	if (inv.firstEmpty() == -1) {
		throw new MyCommandException("§cInventory full!");
	}
	return inv;
}
 
Example 17
Source File: ItemShortcut.java    From Minepacks with GNU General Public License v3.0 5 votes vote down vote up
private void addItem(Player player)
{
	if(player.hasPermission(Permissions.USE))
	{
		boolean empty = false, item = false;
		for(ItemStack itemStack : player.getInventory())
		{
			if(itemStack == null || itemStack.getType() == Material.AIR) empty = true;
			else if(isItemShortcut(itemStack))
			{
				item = true;
				break;
			}
		}
		if(!item && empty)
		{
			if(preferredSlotId >= 0 && preferredSlotId < 36)
			{
				ItemStack stack = player.getInventory().getItem(preferredSlotId);
				if(stack == null || stack.getType() == Material.AIR)
				{
					player.getInventory().setItem(preferredSlotId, HeadUtils.fromBase64(value, itemName, MINEPACKS_UUID));
					return;
				}
			}
			player.getInventory().addItem(HeadUtils.fromBase64(value, itemName, MINEPACKS_UUID));
		}
	}
}
 
Example 18
Source File: ViewInventoryMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void updateMonitoredClick(final InventoryClickedEvent event) {
    if(event.getWhoClicked() instanceof Player) {
        Player player = (Player) event.getWhoClicked();

        boolean playerInventory = event.getInventory().getType() == InventoryType.CRAFTING; // cb bug fix
        Inventory inventory;

        if(playerInventory) {
            inventory = player.getInventory();
        } else {
            inventory = event.getInventory();
        }

        invLoop: for(Map.Entry<Player, View> entry : new HashSet<>(this.views.entrySet())) { // avoid ConcurrentModificationException
            final Player viewer = entry.getKey();
            View view = entry.getValue();

            // because a player can only be viewing one inventory at a time,
            // this is how we determine if we have a match
            if(inventory.getViewers().isEmpty() ||
               view.watched.getViewers().isEmpty() ||
               inventory.getViewers().size() > view.watched.getViewers().size()) continue invLoop;

            for(int i = 0; i < inventory.getViewers().size(); i++) {
                if(!inventory.getViewers().get(i).equals(view.watched.getViewers().get(i))) {
                    continue invLoop;
                }
            }

            // a watched user is in a chest
            if(view.isPlayerInventory() && !playerInventory) {
                inventory = view.getPlayerInventory().getHolder().getInventory();
                playerInventory = true;
            }

            if(playerInventory) {
                this.previewPlayerInventory(viewer, (PlayerInventory) inventory);
            } else {
                this.previewInventory(viewer, inventory);
            }
        }
    }
}
 
Example 19
Source File: PlayerStateHolder.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public void updateState(Player player, boolean location, GameMode mode) {
	PlayerInventory inventory = player.getInventory();
       boolean is1_9 = MinecraftVersion.getImplementationVersion().compareTo(MinecraftVersion.V1_9) >= 0;
       boolean isSimpleSize = inventory.getContents().length <= SIMPLE_INVENTORY_SIZE;

       ItemStack[] contents = inventory.getContents();
       ItemStack[] inventoryArray = new ItemStack[is1_9 && !isSimpleSize ? inventory.getSize() : INVENTORY_SIZE];

       if (!is1_9 || isSimpleSize) {
           ItemStack[] armor = inventory.getArmorContents();
           System.arraycopy(contents, 0, inventoryArray, 0, contents.length);
           System.arraycopy(armor, 0, inventoryArray, inventoryArray.length - ARMOR_INVENTORY_SIZE, armor.length);
       } else {
           System.arraycopy(contents, 0, inventoryArray, 0, contents.length);
       }
	
	/* Initialize the state with the current player state */
	setInventory(inventoryArray);
	setOnCursor(player.getItemOnCursor());
	setGamemode(mode != null ? mode : player.getGameMode());
       setMaxHealth(player.getMaxHealth());
	setHealth(player.getHealth(), player.getMaxHealth());
	setFoodLevel(player.getFoodLevel());
	setLevel(player.getLevel());
	setExperience(player.getExp());
	setAllowFlight(player.getAllowFlight());
	setFlying(player.isFlying());
	setActiveEffects(player.getActivePotionEffects());
	setExhaustion(player.getExhaustion());
	setSaturation(player.getSaturation());
	setFallDistance(player.getFallDistance());
	setFireTicks(player.getFireTicks());
	
	if (location) {
		setLocation(player.getLocation());
	}
	
	setScoreboard(player.getScoreboard());
	setCompassTarget(player.getCompassTarget());
	
	List<WeakReference<Player>> cantSee = Lists.newArrayList();
	for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
		if (player.canSee(onlinePlayer)) {
			continue;
		}
		
		WeakReference<Player> ref = new WeakReference<Player>(onlinePlayer);
		cantSee.add(ref);
	}
	
	setCantSee(cantSee);
}
 
Example 20
Source File: Soulbound.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void effect(PlayerDeathEvent event) {
	if (event.getKeepInventory()) {
		return;
	}

	Player player = event.getEntity();
	Inventory inventory = player.getInventory();

	for (ItemStack itemStack : inventory.getContents()) {
		if (itemStack == null) {
			continue; // More consistent nullability in NotNull fields
		}

		if (modManager.isArmorViable(itemStack) || modManager.isToolViable(itemStack) || modManager.isWandViable(itemStack)) {
			if (!player.hasPermission("minetinker.modifiers.soulbound.use")) {
				continue;
			}

			if (!modManager.hasMod(itemStack, this)) {
				continue;
			}

			Random rand = new Random();
			int n = rand.nextInt(100);
			int c = modManager.getModLevel(itemStack, this) * percentagePerLevel;
			ChatWriter.logModifier(player, event, this, itemStack, String.format("Chance(%d/%d)", n, c));
			if (n > c) {
				continue;
			}

			storedItemStacks.computeIfAbsent(player.getUniqueId(), k -> new ArrayList<>()); // ?

			ArrayList<ItemStack> stored = storedItemStacks.get(player.getUniqueId());

			if (stored.contains(itemStack)) {
				continue;
			}

			if (decrementModLevelOnUse) {
				int newLevel = modManager.getModLevel(itemStack, this) - 1;

				if (newLevel == 0) {
					modManager.removeMod(itemStack, this);
				} else {
					DataHandler.setTag(itemStack, getKey(), modManager.getModLevel(itemStack, this) - 1, PersistentDataType.INTEGER, false);
				}
			}

			stored.add(itemStack.clone());
			itemStack.setAmount(0);
		}
	}
}