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

The following examples show how to use org.bukkit.entity.Player#updateInventory() . 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: 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 2
Source File: MatchManager.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
private void prepareSpectateInv(Player player, GameMap gameMap) {
	int slot = 9;
       for (Player player1: gameMap.getAlivePlayers()) {
           if (player1 != null) {
            ItemStack playerhead1 = SkyWarsReloaded.getNMS().getBlankPlayerHead();
    		SkullMeta meta1 = (SkullMeta)playerhead1.getItemMeta();
    		SkyWarsReloaded.getNMS().updateSkull(meta1, player1);
    		meta1.setDisplayName(ChatColor.YELLOW + player1.getName());
    		List<String> lore = new ArrayList<>();
    		lore.add(new Messaging.MessageFormatter().setVariable("player", player1.getName()).format("spectate.playeritemlore"));
    		meta1.setLore(lore);
    		playerhead1.setItemMeta(meta1);
    		if (player != null) {
				player.getInventory().setItem(slot, playerhead1);
			} else {
    			break;
			}
    		slot++;
           }
       }
	if (player != null) {
		player.updateInventory();
	}
}
 
Example 3
Source File: TakeBrewEvent.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {

    Player p = PlayerConverter.getPlayer(playerID);

    int remaining = count;

    for (int i = 0; i < p.getInventory().getSize(); i++) {
        ItemStack item = p.getInventory().getItem(i);
        if (item != null && Brew.get(item) != null && Brew.get(item).getCurrentRecipe().equals(brew)) {
            if (item.getAmount() - remaining <= 0) {
                remaining -= item.getAmount();
                p.getInventory().setItem(i, null);
            } else {
                item.setAmount(item.getAmount() - remaining);
                remaining = 0;
            }
            if (remaining <= 0) {
                break;
            }
        }
    }
    p.updateInventory();
    return null;
}
 
Example 4
Source File: ArmorListener.java    From AdditionsAPI with MIT License 6 votes vote down vote up
@EventHandler(priority =  EventPriority.HIGHEST, ignoreCancelled = true)
public void playerInteractEvent(PlayerInteractEvent e){
	if(e.getAction() == Action.PHYSICAL) return;
	if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK){
		Player player = e.getPlayer();
		ArmorType newArmorType = ArmorType.matchType(e.getItem());
		if(newArmorType != null){
			if(newArmorType.equals(ArmorType.HELMET) && isAirOrNull(e.getPlayer().getInventory().getHelmet()) || newArmorType.equals(ArmorType.CHESTPLATE) && isAirOrNull(e.getPlayer().getInventory().getChestplate()) || newArmorType.equals(ArmorType.LEGGINGS) && isAirOrNull(e.getPlayer().getInventory().getLeggings()) || newArmorType.equals(ArmorType.BOOTS) && isAirOrNull(e.getPlayer().getInventory().getBoots())){
				ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(e.getPlayer(), EquipMethod.HOTBAR, ArmorType.matchType(e.getItem()), null, e.getItem());
				Bukkit.getServer().getPluginManager().callEvent(armorEquipEvent);
				if(armorEquipEvent.isCancelled()){
					e.setCancelled(true);
					player.updateInventory();
				}
			}
		}
	}
}
 
Example 5
Source File: MainListener.java    From ArmorStandTools with MIT License 5 votes vote down vote up
@EventHandler
public void onCraftItem(CraftItemEvent event) {
    if (event.isCancelled()) return;
    final Player p = (Player) event.getWhoClicked();
    CraftingInventory inventory = event.getInventory();
    for(ItemStack is : inventory.getContents()) {
        if(ArmorStandTool.isTool(is)) {
            event.setCancelled(true);
            //noinspection deprecation
            p.updateInventory();
            return;
        }
    }
}
 
Example 6
Source File: Game.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
public void playerJoinTeam(Player player, Team team) {
  if (team.getPlayers().size() >= team.getMaxPlayers()) {
    player.sendMessage(
        ChatWriter.pluginMessage(ChatColor.RED + BedwarsRel._l(player, "errors.teamfull")));
    return;
  }

  if (team.addPlayer(player)) {
    this.nonFreePlayer(player);

    // Team color chestplate
    ItemStack chestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
    LeatherArmorMeta meta = (LeatherArmorMeta) chestplate.getItemMeta();
    meta.setColor(team.getColor().getColor());
    meta.setDisplayName(team.getChatColor() + team.getDisplayName());
    chestplate.setItemMeta(meta);

    player.getInventory().setItem(7, chestplate);
    player.updateInventory();
  } else {
    player.sendMessage(
        ChatWriter.pluginMessage(ChatColor.RED + BedwarsRel._l(player, "errors.teamfull")));
    return;
  }

  this.updateScoreboard();

  if (this.isStartable() && this.getLobbyCountdown() == null) {
    GameLobbyCountdown lobbyCountdown = new GameLobbyCountdown(this);
    lobbyCountdown.runTaskTimer(BedwarsRel.getInstance(), 20L, 20L);
    this.setLobbyCountdown(lobbyCountdown);
  }

  player
      .sendMessage(ChatWriter.pluginMessage(ChatColor.GREEN + BedwarsRel
          ._l(player, "lobby.teamjoined",
              ImmutableMap.of("team", team.getDisplayName() + ChatColor.GREEN))));
}
 
Example 7
Source File: FlagQueueLobby.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe(priority = Subscribe.Priority.MONITOR)
public void onQueueEnter(PlayerEnterQueueEvent event) {
	if (event.isCancelled()) {
		return;
	}
	
	Location teleportPoint = getValue();
	
	SpleefPlayer player = event.getPlayer();
	Player bukkitPlayer = player.getBukkitPlayer();
	
	PlayerStateHolder holder = new PlayerStateHolder();
	holder.setLocation(bukkitPlayer.getLocation());
	holder.setGamemode(bukkitPlayer.getGameMode());
	
	bukkitPlayer.setGameMode(GameMode.SURVIVAL);
	player.teleport(teleportPoint);
	
	holder.updateState(bukkitPlayer, false, holder.getGamemode());
	player.savePlayerState(this, holder);

       boolean adventureMode = config.getGeneralSection().isAdventureMode();
	PlayerStateHolder.applyDefaultState(bukkitPlayer, adventureMode);
	
	MaterialData data = config.getFlagSection().getLeaveItem();
	if (data != null) {
		MetadatableItemStack stack = new MetadatableItemStack(data.toItemStack(1));
		ItemMeta meta = stack.getItemMeta();
		meta.setDisplayName(getI18N().getString(Messages.Player.LEAVE_QUEUE_DISPLAYNAME));
		meta.setLore(Lists.newArrayList(getI18N().getString(Messages.Player.LEAVE_QUEUE_LORE)));
		stack.setItemMeta(meta);

		stack.setMetadata(LEAVE_ITEM_KEY, null);

		bukkitPlayer.getInventory().setItem(RIGHT_HOTBAR_SLOT, stack);
		bukkitPlayer.updateInventory();
	}
}
 
Example 8
Source File: Utils.java    From ArmorStandTools with MIT License 5 votes vote down vote up
static void cycleInventory(Player p) {
    Inventory i = p.getInventory();
    ItemStack temp;
    for (int n = 0; n < 9; n++) {
        temp = i.getItem(n);
        i.setItem(n, i.getItem(27 + n));
        i.setItem(27 + n, i.getItem(18 + n));
        i.setItem(18 + n, i.getItem(9 + n));
        i.setItem(9 + n, temp);
    }
    //noinspection deprecation
    p.updateInventory();
}
 
Example 9
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 10
Source File: Resident.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public boolean takeItem(int itemId, int itemData, int amount) throws CivException {
	Player player = CivGlobal.getPlayer(this);
	Inventory inv = player.getInventory();

	if (!inv.contains(itemId)) {
		return false;
	}
	
	HashMap<Integer, ? extends ItemStack> stacks;
	stacks = inv.all(itemId);
	
	for (ItemStack stack : stacks.values()) {
		if (stack.getData().getData() != (byte)itemData) {
			continue;
		}
		
		if (stack.getAmount() <= 0)
			continue;
		
		if (stack.getAmount() < amount) {
			amount -= stack.getAmount();
			stack.setAmount(0);
			inv.removeItem(stack);
			continue;
		}
		else {			
			stack.setAmount(stack.getAmount()-amount);
			break;
		}
	}
	
	player.updateInventory();
	return true;
}
 
Example 11
Source File: SpigotStuff.java    From ProtocolSupportPocketStuff with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void sendPlayerSkin(Player player, SkinDataWrapper skindata) {
	Connection connection = ProtocolSupportAPI.getConnection(player);
	EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
	connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, entityPlayer));
	DimensionManager dimThing = null;
	switch (player.getWorld().getEnvironment()) {
	case NETHER:
		dimThing = DimensionManager.NETHER;
		break;
	case NORMAL:
		dimThing = DimensionManager.OVERWORLD;
		break;
	case THE_END:
		dimThing = DimensionManager.THE_END;
		break;
	}
	connection.sendPacket(new PacketPlayOutRespawn(dimThing, entityPlayer.world.getDifficulty(), WorldType.NORMAL, EnumGamemode.getById(player.getGameMode().getValue())));
	player.setHealth(player.getHealth());
	player.setMaxHealth(player.getMaxHealth());
	player.setFlying(player.isFlying());
	player.teleport(player.getLocation());
	player.setLevel(player.getLevel());
	player.setExp(player.getExp());
	player.updateInventory();
	connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, entityPlayer));
}
 
Example 12
Source File: Resident.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public boolean takeItemInHand(int itemId, int itemData, int amount) throws CivException {
	Player player = CivGlobal.getPlayer(this);
	Inventory inv = player.getInventory();

	if (!inv.contains(itemId)) {
		return false;
	}

	if ((player.getItemInHand().getTypeId() != itemId) &&
			(player.getItemInHand().getTypeId() != itemData)) {
		return false;
	}
	
	ItemStack stack = player.getItemInHand();
	
	if (stack.getAmount() < amount) {
		return false;
	} else if (stack.getAmount() == amount) {
		inv.removeItem(stack);
	} else {
		stack.setAmount(stack.getAmount() - amount);
	}
	
	player.updateInventory();
	return true;
}
 
Example 13
Source File: FlagTrackingSpectate.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
private void addTrackingCompass(Player player) {
    MetadatableItemStack compass = new MetadatableItemStack(Material.COMPASS);
    ItemMeta meta = compass.getItemMeta();
    meta.setDisplayName(getI18N().getString(Messages.Player.TRACKER));
    meta.setLore(Lists.newArrayList(getI18N().getString(Messages.Player.TRACKER_LORE)));
    compass.setItemMeta(meta);
    compass.setMetadata(TRACKER_KEY, null);

    Inventory inventory = player.getInventory();
    inventory.setItem(ITEM_SLOT, compass);
    player.updateInventory();
}
 
Example 14
Source File: IconMenu.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void update(Player player) {
   	InventoryView inventory = player.getOpenInventory();
   	if (inventory != null) {
           for (int iii = 0; iii < this.optionIcons.length; iii++) {
               if (this.optionIcons[iii] != null) {
                   inventory.setItem(iii, this.optionIcons[iii]);
               }
           }
           player.updateInventory();
   	}
   }
 
Example 15
Source File: Recipes.java    From ProRecipes with GNU General Public License v2.0 4 votes vote down vote up
public boolean handleDoubles(ItemStack[] items, ItemStack result, Player p, Inventory inv){
	//long mil = System.currentTimeMillis();
	RecipeShapeless r = new RecipeShapeless(new ItemStack(Material.ANVIL));
	
	for(ItemStack i : items){
		if(i != null && i.getType() != Material.AIR){
			r.addIngredient(i);
		}
	}
	
	r.removeIngredient(result);
	int ing = 0;
	
	RecipeShapeless fina = null;
	for(RecipeShapeless recipe : shapeless){
		if(recipe.matchLowest(r)){
			if(recipe.ingredientCount() >= ing){
				ing = recipe.ingredientCount();
			}else{
				continue;
			}
	
			if(recipe.hasPermission()){
				if(!p.hasPermission(recipe.getPermission())){
					continue;
				}
			}
			
			fina = recipe;
			
		}
	
	}
	
	if(fina != null){
		
		ItemStack old = result;
		
		WorkbenchCraftEvent workbenchEvent = new WorkbenchCraftEvent(ProRecipes.getAPI().getRecipe(RecipeType.SHAPELESS, shapeless.indexOf(fina)), p, inv, fina.getResult());
		ProRecipes.getPlugin().getServer().getPluginManager().callEvent(workbenchEvent);
				
		if(old != null){
			if(!old.isSimilar(fina.getResult())){
				p.updateInventory();
			}
		}
		//System.out.println("Milliseconds spent (handleDoubles): " + (mil - System.currentTimeMillis()));
		return true;
	}
	//System.out.println("Milliseconds spent (handleDoubles): " + (mil - System.currentTimeMillis()));
	return false;
	
}
 
Example 16
Source File: UHPluginListener.java    From KTP with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteract(PlayerInteractEvent ev) {
	if ((ev.getAction() == Action.RIGHT_CLICK_AIR || ev.getAction() == Action.RIGHT_CLICK_BLOCK) && ev.getPlayer().getItemInHand().getType() == Material.COMPASS && p.getConfig().getBoolean("compass")) {
		Player pl = ev.getPlayer();
		Boolean foundRottenFlesh = false;
		for (ItemStack is : pl.getInventory().getContents()) {
			if (is != null && is.getType() == Material.ROTTEN_FLESH) {
				p.getLogger().info(""+is.getAmount());
				if (is.getAmount() != 1) is.setAmount(is.getAmount()-1);
				else { p.getLogger().info("lol"); pl.getInventory().removeItem(is); }
				pl.updateInventory();
				foundRottenFlesh = true;
				break;
			}
		}
		if (!foundRottenFlesh) {
			pl.sendMessage(ChatColor.GRAY+""+ChatColor.ITALIC+"Vous n'avez pas de chair de zombie.");
			pl.playSound(pl.getLocation(), Sound.BLOCK_WOOD_STEP, 1F, 1F);
			return;
		}
		pl.playSound(pl.getLocation(), Sound.ENTITY_PLAYER_BURP, 1F, 1F);
		Player nearest = null;
		Double distance = 99999D;
		for (Player pl2 : p.getServer().getOnlinePlayers()) {
			try {	
				Double calc = pl.getLocation().distance(pl2.getLocation());
				if (calc > 1 && calc < distance) {
					distance = calc;
					if (pl2 != pl && !this.p.inSameTeam(pl, pl2)) nearest = pl2.getPlayer();
				}
			} catch (Exception e) {}
		}
		if (nearest == null) {
			pl.sendMessage(ChatColor.GRAY+""+ChatColor.ITALIC+"Seul le silence comble votre requĂȘte.");
			return;
		}
		pl.sendMessage(ChatColor.GRAY+"La boussole pointe sur le joueur le plus proche.");
		pl.setCompassTarget(nearest.getLocation());
	}
}
 
Example 17
Source File: BiomesPanel.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
    Player player = (Player) event.getWhoClicked(); // The player that
    // clicked the item
    UUID playerUUID = player.getUniqueId();
    Inventory inventory = event.getInventory(); // The inventory that was
    // clicked in
    int slot = event.getRawSlot();
    // Check this is the right panel
    if (inventory.getName() == null || !inventory.getName().equals(plugin.myLocale().biomePanelTitle)) {
        return;
    }
    if (slot == -999) {
        inventory.clear();
        player.closeInventory();
        event.setCancelled(true);
        return;
    }
    if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
        event.setCancelled(true);
        inventory.clear();
        player.closeInventory();
        player.updateInventory();
        return;
    }

    // Get the list of items for this player
    List<BiomeItem> thisPanel = biomeItems.get(player.getUniqueId());
    if (thisPanel == null) {
        inventory.clear();
        player.closeInventory();
        event.setCancelled(true);
        return;
    }
    if (slot >= 0 && slot < thisPanel.size()) {
        event.setCancelled(true);
        // plugin.getLogger().info("DEBUG: slot is " + slot);
        // Do something
        // Check this player has an island
        Island island = plugin.getGrid().getIsland(playerUUID);
        if (island == null) {
            Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoIsland);
            return;
        }
        // Check ownership
        if (!island.getOwner().equals(playerUUID)) {
            Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).levelerrornotYourIsland);
            return; 
        }
        if (!plugin.getGrid().playerIsOnIsland(player)) {
            Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotOnIsland);
            return;
        }
        Biome biome = thisPanel.get(slot).getBiome();
        if (biome != null) {
            event.setCancelled(true);
            if (Settings.useEconomy) {
                // Check cost
                double cost = thisPanel.get(slot).getPrice();
                if (cost > 0D) {
                    if (!VaultHelper.econ.has(player, Settings.worldName, cost)) {
                        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).minishopYouCannotAfford.replace("[description]", VaultHelper.econ.format(cost)));
                        return;
                    } else {
                        VaultHelper.econ.withdrawPlayer(player, Settings.worldName, cost);
                        Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).biomeYouBought.replace("[cost]", VaultHelper.econ.format(cost)));
                    }
                }
            }
        }
        inventory.clear();
        player.closeInventory(); // Closes the inventory
        // Actually set the biome
        Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).biomePleaseWait);
        new SetBiome(plugin, island, biome, player);
    }
    return;
}
 
Example 18
Source File: ASkyBlock.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resets a player's inventory, armor slots, equipment, enderchest and
 * potion effects
 *
 * @param player - player
 */
@SuppressWarnings("deprecation")
public void resetPlayer(Player player) {
    // getLogger().info("DEBUG: clear inventory = " +
    // Settings.clearInventory);
    if (Settings.clearInventory
            && (player.getWorld().getName().equalsIgnoreCase(Settings.worldName) || player.getWorld().getName()
                    .equalsIgnoreCase(Settings.worldName + "_nether"))) {
        // Clear their inventory and equipment and set them as survival
        player.getInventory().clear(); // Javadocs are wrong - this does not
        // clear armor slots! So...
        player.getInventory().setArmorContents(null);
        player.getInventory().setHelmet(null);
        player.getInventory().setChestplate(null);
        player.getInventory().setLeggings(null);
        player.getInventory().setBoots(null);
        player.getEquipment().clear();
    }
    if (!player.isOp()) {
        player.setGameMode(GameMode.SURVIVAL);
    }
    if (Settings.resetChallenges) {
        // Reset the player's challenge status
        players.resetAllChallenges(player.getUniqueId(), false);
    }
    // Reset the island level
    players.setIslandLevel(player.getUniqueId(), 0);
    // Clear the starter island
    players.clearStartIslandRating(player.getUniqueId());
    // Save the player
    players.save(player.getUniqueId());
    topTen.topTenAddEntry(player.getUniqueId(), 0);
    // Update the inventory
    player.updateInventory();
    if (Settings.resetEnderChest) {
        // Clear any Enderchest contents
        final ItemStack[] items = new ItemStack[player.getEnderChest().getContents().length];
        player.getEnderChest().setContents(items);
    }
    // Clear any potion effects
    for (PotionEffect effect : player.getActivePotionEffects())
        player.removePotionEffect(effect.getType());
}
 
Example 19
Source File: UnitMaterial.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void onInvItemDrop(InventoryClickEvent event,
		Inventory toInv, ItemStack stack) {
	
	if (toInv.getHolder() instanceof Player) {
		//A hack to make sure we are always moving the item to the player's inv.
		//A player inv is always on the bottom, toInv could be the 'crafting' inv 
		toInv = event.getView().getBottomInventory();
		Player player = (Player)toInv.getHolder();
			
		if(!validateUnitUse(player, stack)) {
			CivMessage.sendError(player, "You cannot use this unit because it does not belong to your civlization.");
			event.setCancelled(true);
			return;
		}
		
		//Prevent dropping in two unit materials.
		ConfigUnit unit = Unit.getPlayerUnit(player);
		if (unit != null) {
			//player already has a unit item, cancel this event.
			CivMessage.sendError(player, "You already are a "+unit.name+" cannot pickup another unit item.");
			event.setCancelled(true);
			event.setResult(Result.DENY);
			event.getView().close();
			player.updateInventory();
			return;
		}
		
		// Reposition item to the last quickbar slot
		if (event.getSlot() != LAST_SLOT) {
			
			DelayMoveInventoryItem task = new DelayMoveInventoryItem();
			task.fromSlot = event.getSlot();
			task.toSlot = LAST_SLOT;
			task.inv = toInv;
			task.playerName = player.getName();
			TaskMaster.syncTask(task);
		}

		onItemToPlayer(player, stack);
	}

}
 
Example 20
Source File: WarpPanel.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onInventoryClick(InventoryClickEvent event) {
    Inventory inventory = event.getInventory(); // The inventory that was clicked in
    if (inventory.getName() == null) {
        return;
    }
    // The player that clicked the item
    final Player player = (Player) event.getWhoClicked();
    String title = inventory.getTitle();
    if (!inventory.getTitle().startsWith(plugin.myLocale().warpsTitle + " #")) {
        return;
    }
    event.setCancelled(true);
    if (event.getSlotType().equals(SlotType.OUTSIDE)) {
        player.closeInventory();
        return;
    }
    if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
        player.closeInventory();
        player.updateInventory();
        return;
    }
    ItemStack clicked = event.getCurrentItem(); // The item that was clicked
    if (DEBUG)
        plugin.getLogger().info("DEBUG: inventory size = " + inventory.getSize());
    if (DEBUG)
        plugin.getLogger().info("DEBUG: clicked = " + clicked);
    if (DEBUG)
        plugin.getLogger().info("DEBUG: rawslot = " + event.getRawSlot());
    if (event.getRawSlot() >= event.getInventory().getSize() || clicked.getType() == Material.AIR) {
        return;
    }
    int panelNumber = 0;
    try {
        panelNumber = Integer.valueOf(title.substring(title.indexOf('#')+ 1));
    } catch (Exception e) {
        panelNumber = 0;
    }
    if (clicked.getItemMeta().hasDisplayName()) {
        String command = ChatColor.stripColor(clicked.getItemMeta().getDisplayName());
        if (DEBUG)
            plugin.getLogger().info("DEBUG: command = " + command);
        if (command != null) {
            if (command.equalsIgnoreCase(ChatColor.stripColor(plugin.myLocale().warpsNext))) {
                player.closeInventory();
                Util.runCommand(player, Settings.ISLANDCOMMAND + " warps " + (panelNumber+1));
            } else if (command.equalsIgnoreCase(ChatColor.stripColor(plugin.myLocale().warpsPrevious))) {
                player.closeInventory();
                Util.runCommand(player, Settings.ISLANDCOMMAND + " warps " + (panelNumber-1));
            } else {
                player.closeInventory();
                Util.sendMessage(player, ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).warpswarpToPlayersSign.replace("<player>", command));
                Util.runCommand(player, Settings.ISLANDCOMMAND + " warp " + command);
            }
        }
    }
}