@Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { String name = args.<String>getOne("name").get(); if (src instanceof Player && EzpzPvpKit.getInstance().isQueueExisting(name)) { Player player = (Player) src; PvPPlayer pvpPlayer = EzpzPvpKit.getInstance().getPlayer(player.getIdentifier()); Team team = EzpzPvpKit.getInstance().getTeam(pvpPlayer.getTeam()); DuelQueue queue = EzpzPvpKit.getInstance().getQueue(name); // Size ? if (team.getSize() != queue.getSize()) Utils.sendKitMessage( player, Text.of(TextColors.RED, "Party size doesn't match queue size")); // Is in duel ? else if (team.getInMatch()) Utils.sendKitMessage(player, Text.of(TextColors.RED, "Cannot join queue in duel")); else { // is in other queue ? if (team.getQueue() != null) EzpzPvpKit.getInstance().getQueue(team.getQueue()).leave(team); queue.join(team); for (String it : team.getPlayers()) Utils.sendKitMessage( EzpzPvpKit.getInstance().getPlayer(it).getPlayer(), Text.of("You joined queue : " + name)); } } else if (src instanceof Player && !EzpzPvpKit.getInstance().isQueueExisting(name)) Utils.sendKitMessage((Player) src, Text.of(TextColors.RED, "this queue doesn't exist")); else if (src instanceof ConsoleSource) Utils.sendMessageC(src); else if (src instanceof CommandBlockSource) Utils.sendMessageCB(src); return CommandResult.success(); }
@Listener public void onPlayerChat(MessageChannelEvent.Chat event) { Optional<Player> playerOptional = event.getCause().first(Player.class); if (!playerOptional.isPresent()) return; Player player = playerOptional.get(); if (JobsLite.optionEnabled("chatPrefixes")) { String uuid = player.getUniqueId().toString(); if (playerManager.playerExists(uuid)) { String currentJob = playerManager.getCurrentJob(uuid).trim(); if (!currentJob.isEmpty()) { String displayName = jobManager.getDisplayName(currentJob); if (!displayName.isEmpty()) { if (JobsLite.optionEnabled("displayLevel")) { event.setMessage( TextUtils.chatMessage( player.getName(), displayName, playerManager.getCurrentLevel(uuid, currentJob), jobManager.getColor(currentJob), event.getRawMessage().toPlain())); } else { event.setMessage( TextUtils.chatMessage( player.getName(), displayName, jobManager.getColor(currentJob), event.getRawMessage().toPlain())); } } } } } }
@Override public CommandResult execute(CommandSource source, CommandContext args) throws CommandException { if (!(source instanceof Player)) { source.sendMessage(Constants.MUST_BE_PLAYER_MSG); return CommandResult.empty(); } Player player = (Player) source; Optional<Warp> optWarp = args.getOne("warp"); if (!optWarp.isPresent()) { source.sendMessage(Constants.WARP_NOT_FOUND_MSG); return CommandResult.empty(); } Warp warp = optWarp.get(); if (this.plugin.getUtil().hasPermission(player, warp) == false) { player.sendMessage(Constants.NO_PERMISSION_MSG); return CommandResult.empty(); } this.plugin.getWarpManager().scheduleWarp(player, warp); return CommandResult.success(); }
public void setReply(Player pl) { reply = pl.getUniqueId(); JsonConfig conf = getPlayerConfig(); conf.set("reply", pl.getUniqueId().toString()); conf.save(); save(); }
@Override public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception { Optional<Player> opl = this.getUser(Player.class, src, player, args); if (!opl.isPresent()) { return CommandResult.empty(); } Player pl = opl.get(); InternalQuickStartUser uc = plugin.getUserLoader().getUser(pl); boolean fly = args.<Boolean>getOne(toggle).orElse(!uc.isFlying()); if (!uc.setFlying(fly)) { src.sendMessages(Text.of(TextColors.RED, Util.getMessageWithFormat("command.fly.error"))); return CommandResult.empty(); } if (pl != src) { src.sendMessages( Text.of( TextColors.GREEN, MessageFormat.format( Util.getMessageWithFormat( fly ? "command.fly.player.on" : "command.fly.player.off"), pl.getName()))); } pl.sendMessage( Text.of( TextColors.GREEN, Util.getMessageWithFormat(fly ? "command.fly.on" : "command.fly.off"))); return CommandResult.success(); }
@Override public CommandResult executeCommand(Player src, CommandContext args) throws Exception { // Get the home. Optional<WarpLocation> owl = args.<WarpLocation>getOne(home); if (!owl.isPresent()) { owl = plugin.getUserLoader().getUser(src).getHome("home"); if (!owl.isPresent()) { src.sendMessage( Text.of(TextColors.RED, Util.getMessageWithFormat("args.home.nohome", "home"))); return CommandResult.empty(); } } WarpLocation wl = owl.get(); // Warp to it safely. if (src.setLocationAndRotationSafely(wl.getLocation(), wl.getRotation())) { src.sendMessage( Text.of( TextColors.GREEN, Util.getMessageWithFormat("command.home.success", wl.getName()))); return CommandResult.success(); } else { src.sendMessage( Text.of(TextColors.RED, Util.getMessageWithFormat("command.home.fail", wl.getName()))); return CommandResult.empty(); } }
public RLocation getSpawn(Boolean firstjoin) { JsonConfig conf = new JsonConfig(UltimateFileLoader.Dspawns); String loc; Player p = r.searchPlayer(uuid); Boolean world = conf.contains("worlds.world." + p.getWorld().getName() + ".global"); String world_ = world ? conf.getString("worlds.world." + p.getWorld().getName() + ".global") : null; Boolean group = r.getVault() != null && r.getVault().getPermission() != null && r.getVault().getPermission().getPrimaryGroup(p) != null && conf.contains("global.group." + r.getVault().getPermission().getPrimaryGroup(p)); String group_ = r.getVault() != null && r.getVault().getPermission() != null && r.getVault().getPermission().getPrimaryGroup(p) != null ? (group ? conf.getString("global.group." + r.getVault().getPermission().getPrimaryGroup(p)) : null) : null; Boolean gw = r.getVault() != null && r.getVault().getPermission() != null && r.getVault().getPermission().getPrimaryGroup(p) != null && conf.contains( "worlds.world." + p.getWorld().getName() + ".group." + r.getVault().getPermission().getPrimaryGroup(p)); String gw_ = r.getVault() != null && r.getVault().getPermission() != null && r.getVault().getPermission().getPrimaryGroup(p) != null ? conf.getString( "worlds.world." + p.getWorld().getName() + ".group." + r.getVault().getPermission().getPrimaryGroup(p)) : null; if (firstjoin && conf.contains("global.firstjoin")) { loc = conf.getString("global.firstjoin"); } else if (gw) { loc = gw_; } else if (world && group) { if (r.getCnfg().getBoolean("Command.Spawn.WorldOrGroup")) { loc = world_; } else { loc = group_; } } else if (world) { loc = world_; } else if (group) { loc = group_; } else if (conf.contains("global")) { loc = conf.getString("global"); } else { return null; } return LocationUtil.convertStringToLocation(loc); }
@Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { Player player = (Player) src; PlayerGymInfoData playerGymInfoData = player.get(PlayerGymInfoData.class).get(); List<ItemStackSnapshot> itemStackSnapshots = playerGymInfoData.badgeItems().get(); InventoryBasic inventoryBasic = new InventoryBasic("Badges", true, 54); for (int i = 0; i < itemStackSnapshots.size(); i++) { if (i < inventoryBasic.getSizeInventory()) { ItemStackSnapshot snapshot = itemStackSnapshots.get(i); ItemStack stack = snapshot.createStack(); inventoryBasic.setInventorySlotContents(i, (net.minecraft.item.ItemStack) stack); } } ((EntityPlayerMP) player).displayGUIChest(inventoryBasic); /* try { GameProfile gameProfile = Sponge.getServer().getGameProfileManager().get("clienthax").get(); // <-- why the hell doesnt this return a optional.. -.- System.out.println(gameProfile.getUniqueId()); } catch (Exception e) { e.printStackTrace(); }*/ return CommandResult.success(); }
@Listener public void onPlayerDeath(DestructEntityEvent event) { if (event.getTargetEntity() instanceof Player) { Player died = (Player) event.getTargetEntity(); Utils.setLastDeathLocation(died.getUniqueId(), died.getLocation()); } }
public static CommandSpec getCommand() { return CommandSpec.builder() .arguments( GenericArguments.player(Text.of("player")), new ChannelArgument(Text.of("channel"))) .description(Text.of("Unban player from channel.")) .permission("darmok.mod") .executor( (source, args) -> { Player player = args.<Player>getOne("player").get(); Channel channel = args.<Channel>getOne("channel").get(); Darmok.getPlayerRegistry().unbanFromChannel(player, channel); player.sendMessage( Format.error( String.format( "You have been unbanned from the %s channel.", channel.getName()))); source.sendMessage( Format.heading( String.format( "You have unbanned %s from channel %s", player.getName(), channel.getName()))); return CommandResult.success(); }) .build(); }
@Listener public void onPlayerDropItem(DropItemEvent.Dispense event, @Root Player player) { if (!ConfigManager.canPlayersDropItems()) { final String playerPolisName = ConfigManager.getTeam(player.getUniqueId()); event .getEntities() .forEach( e -> { String isClaimed = ConfigManager.isClaimed(e.getLocation()); if (!isClaimed.equals("false")) { if (playerPolisName == null || !playerPolisName.equals(isClaimed)) { player.sendMessage( Text.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "You cannot drop items in claimed areas.")); event.setCancelled(true); return; } } }); } }
public void revertActiveVisual(Player player) { if (this.visualRevertTask != null) { this.visualRevertTask.cancel(); } if (this.visualClaimId != null) { Claim claim = GriefPrevention.instance.dataStore.getClaim(this.worldProperties, this.visualClaimId); if (claim != null) { claim.playersWatching.remove(this.playerID); } } this.visualClaimId = null; if (this.visualBlocks == null || !player .getWorld() .equals(this.visualBlocks.get(0).getFinal().getLocation().get().getExtent())) { return; } for (int i = 0; i < this.visualBlocks.size(); i++) { BlockSnapshot snapshot = this.visualBlocks.get(i).getOriginal(); player.sendBlockChange(snapshot.getPosition(), snapshot.getState()); } }
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException { if (src instanceof Player) { Player player = (Player) src; ExperienceHolderData expHolderData = player.getOrCreate(ExperienceHolderData.class).get(); player.sendMessage( Text.of( TextColors.GOLD, "Your current experience: ", TextColors.GRAY, expHolderData.totalExperience().get())); player.sendMessage( Text.of( TextColors.GOLD, "Experience to next level: ", TextColors.GRAY, expHolderData.getExperienceBetweenLevels().get() - expHolderData.experienceSinceLevel().get())); } else { src.sendMessage( Text.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command!")); } return CommandResult.success(); }
@Override public void sendTitle(Title title) { checkNotNull(title, "title"); for (Player player : getPlayers()) { player.sendTitle(title); } }
PingRecord() { final Collection<Player> onlinePlayers = SpongeImpl.getGame().getServer().getOnlinePlayers(); int totalPing = 0; for (Player player : onlinePlayers) { totalPing += player.getConnection().getLatency(); } this.avg = onlinePlayers.isEmpty() ? 0 : totalPing / onlinePlayers.size(); }
@Override public void sendMessage(ChatType type, Text message) { checkNotNull(type, "type"); checkNotNull(message, "message"); for (Player player : this.getPlayers()) { player.sendMessage(type, message); } }
@Listener(order = Order.LATE) public void onMessageChannelEventChat(MessageChannelEvent.Chat event, @First Player player) { Builder playerTag = Text.builder().onHover(TextActions.showText(Text.of(player.getName()))); Optional<PlayerTag> optionalPlayerTag = PlayerTag.get(player); if (!optionalPlayerTag.isPresent()) { playerTag.append(PlayerTag.getDefault(player)); } else { playerTag.append(optionalPlayerTag.get().getTag()); } Text worldTag = Text.EMPTY; Optional<WorldTag> optionalWorldTag = WorldTag.get(player.getWorld().getProperties()); if (optionalWorldTag.isPresent()) { worldTag = optionalWorldTag.get().getTag(); } Builder groupTagBuilder = Text.builder(); for (Entry<Set<Context>, List<Subject>> parent : player.getSubjectData().getAllParents().entrySet()) { for (Subject subject : parent.getValue()) { String group = subject.getIdentifier(); if (group.equalsIgnoreCase("op_0") || group.equalsIgnoreCase("op_1") || group.equalsIgnoreCase("op_2") || group.equalsIgnoreCase("op_3") || group.equalsIgnoreCase("op_4")) { group = "op"; } Optional<GroupTag> optionalGroupTag = GroupTag.get(group); if (optionalGroupTag.isPresent()) { groupTagBuilder.append(optionalGroupTag.get().getTag()); } } } MessageFormatter formatter = event.getFormatter(); String oldStr = TextSerializers.FORMATTING_CODE.serialize(formatter.getHeader().toText()); String name = oldStr.substring(oldStr.indexOf("<"), oldStr.lastIndexOf(">") + 1); Text old = TextSerializers.FORMATTING_CODE.deserialize(oldStr.replace(name, "")); formatter.setHeader( TextTemplate.of( worldTag, groupTagBuilder.build(), playerTag.build(), old, TextColors.RESET)); }
public void createBlockBag(Player creator, BlockBag blockBag) { if (getBlockBag(creator.getUniqueId(), blockBag.simpleName) != null) { creator.sendMessage(Text.of(TextColors.RED, "A blockbag with this name already exists!")); return; } blockBag.blockBagId = getUnusedID(); blockBags = Arrays.copyOf(blockBags, blockBags.length + 1); blockBags[blockBags.length - 1] = blockBag; }
@Listener public void onPlayerRespawn(RespawnPlayerEvent event) { Player player = event.getTargetEntity(); if (this.teamA.contains(player)) { event.setToTransform( event.getToTransform().setLocation(this.arena.getTeamASpawn().getLocation())); Sponge.getScheduler() .createTaskBuilder() .execute( () -> { if (this.arena.getTeamALoadout() != null) UltimateGames.game .getCommandManager() .process( Sponge.getServer().getConsole(), "kit " + this.arena.getTeamALoadout() + " " + player.getName()); }) .delayTicks(10) .name("UltimateGames - Give Player Loadout") .submit( UltimateGames.game .getPluginManager() .getPlugin("io.github.hsyyid.ultimategames") .get() .getInstance() .get()); } else if (this.teamB.contains(player)) { event.setToTransform( event.getToTransform().setLocation(this.arena.getTeamBSpawn().getLocation())); Sponge.getScheduler() .createTaskBuilder() .execute( () -> { if (this.arena.getTeamBLoadout() != null) UltimateGames.game .getCommandManager() .process( Sponge.getServer().getConsole(), "kit " + this.arena.getTeamBLoadout() + " " + player.getName()); }) .delayTicks(10) .name("UltimateGames - Give Player Loadout") .submit( UltimateGames.game .getPluginManager() .getPlugin("io.github.hsyyid.ultimategames") .get() .getInstance() .get()); } }
@Listener(order = Order.FIRST) public void onPlayerChat(MessageChannelEvent.Chat event, @First Player player) { String message = event.getRawMessage().toPlain(); if (player.getUniqueId().equals(uuid)) { if (message.equalsIgnoreCase("[cancel]")) { // Cancel the creation cancel(); player.sendMessage(messages.getMessage("creation.cancelled")); } } }
@Listener public void onInventoryClose(InteractInventoryEvent.Close event, @First Player player) { if ((event.getTargetInventory().equals(this.container))) { if (this.users.contains(player.getUniqueId())) { this.users.remove(player.getUniqueId()); if (this.users.isEmpty()) { em.removeListener(owner, this); // no user left to check } this.onClose.forEach(Runnable::run); } } }
@Listener public void onStopped(MinigameStoppedEvent event) { if (event.getMinigame().equals(this)) { for (Player player : players()) { player.setScoreboard(null); if (this.teamAPoints > this.teamBPoints) player.sendMessage( Text.of( TextColors.BLUE, "[UltimateGames]: ", TextColors.GREEN, "Team A has won the Deathmatch!")); else if (this.teamBPoints > this.teamAPoints) player.sendMessage( Text.of( TextColors.BLUE, "[UltimateGames]: ", TextColors.GREEN, "Team B has won the Deathmatch!")); else player.sendMessage( Text.of( TextColors.BLUE, "[UltimateGames]: ", TextColors.GRAY, "The deathmatch has ended with a draw!")); player.sendMessage( Text.of( TextColors.BLUE, "[UltimateGames]: ", TextColors.GREEN, "Deathmatch has ended!")); if (player .getWorld() .getUniqueId() .equals(this.arena.getSpawn().getLocation().getExtent().getUniqueId())) { player.setLocation(this.arena.getSpawn().getLocation()); } else { player.transferToWorld( this.arena.getSpawn().getLocation().getExtent().getUniqueId(), this.arena.getSpawn().getLocation().getPosition()); } player.sendMessage( Text.of( TextColors.BLUE, "[UltimateGames]: ", TextColors.GREEN, "Teleported back to lobby.")); } } }
@Override public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException { int expLevel = ctx.<Integer>getOne("exp").get(); Player player = ctx.<Player>getOne("target").get(); player.offer(Keys.TOTAL_EXPERIENCE, player.get(Keys.TOTAL_EXPERIENCE).get() - expLevel); src.sendMessage( Text.of( TextColors.GREEN, "Success! ", TextColors.YELLOW, "Took " + expLevel + " experience from " + player.getName() + ".")); return CommandResult.success(); }
@Override public CommandResult process(CommandSource sender, String arguments) throws CommandException { String[] args = arguments.split(" "); if (!PermissionsUtils.has(sender, "core.heal")) { sender.sendMessage( Text.builder("You do not have permissions!").color(TextColors.RED).build()); return CommandResult.success(); } if (args.length > 1) { sender.sendMessage(Text.of(TextColors.YELLOW, "Usage: ", TextColors.GRAY, "/heal [player]")); return CommandResult.success(); } if (arguments.equalsIgnoreCase("")) { if (sender instanceof Player == false) { sender.sendMessage( Text.builder("Cannot be run by the console!").color(TextColors.RED).build()); return CommandResult.success(); } Player p = (Player) sender; double max = p.get(Keys.MAX_HEALTH).get(); p.offer(Keys.HEALTH, max); sender.sendMessage(Text.of(TextColors.YELLOW, "You ", TextColors.GRAY, "have been healed.")); } else if (args.length == 1) { if (!PermissionsUtils.has(sender, "core.heal-others")) { sender.sendMessage( Text.builder("You do not have permissions to heal other players!") .color(TextColors.RED) .build()); return CommandResult.success(); } Player p = ServerUtils.getPlayer(args[0]); if (p == null) { sender.sendMessage(Text.builder("Player not found!").color(TextColors.RED).build()); return CommandResult.success(); } double max = p.get(Keys.MAX_HEALTH).get(); p.offer(Keys.HEALTH, max); sender.sendMessage( Text.of(TextColors.YELLOW, p.getName(), TextColors.GRAY, " has been healed.")); p.sendMessage( Text.of( TextColors.GRAY, "You have been healed by ", TextColors.YELLOW, sender.getName())); } return CommandResult.success(); }
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException { if (src instanceof Player) { Player player = (Player) src; if (Utils.isSpawnInConfig()) { if (!Objects.equals(player.getWorld().getName(), Utils.getSpawnWorldName())) { Vector3d position = new Vector3d( Utils.getSpawn(player).getX(), Utils.getSpawn(player).getY(), Utils.getSpawn(player).getZ()); player.transferToWorld(Utils.getSpawnWorldName(), position); src.sendMessage( Texts.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Teleported to Spawn")); return CommandResult.success(); } else { Location<World> spawn = new Location<>( player.getWorld(), Utils.getSpawn(player).getX(), Utils.getSpawn(player).getY(), Utils.getSpawn(player).getZ()); player.setLocation(spawn); } src.sendMessage( Texts.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Teleported to Spawn")); } else { src.sendMessage( Texts.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Spawn has not been set yet!")); } } else if (src instanceof ConsoleSource) { src.sendMessage( Texts.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /spawn!")); } else if (src instanceof CommandBlockSource) { src.sendMessage( Texts.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /spawn!")); } return CommandResult.success(); }
@Override public Optional<Text> getValue(@Nullable Object player) { if (player == null) return Optional.empty(); if (player instanceof Player) { Player p = (Player) player; if (Sponge.getServiceManager().provide(EconomyService.class).isPresent()) { EconomyService es = Sponge.getServiceManager().provide(EconomyService.class).get(); if (es.getOrCreateAccount(p.getUniqueId()).isPresent()) { BigDecimal balance = es.getOrCreateAccount(p.getUniqueId()).get().getBalance(es.getDefaultCurrency()); return Optional.of(Text.of(balance.toString())); } } return Optional.empty(); } return Optional.empty(); }
@Listener(order = Order.POST) public void onAffectSlotEvent(AffectSlotEvent event, @Root Player player) { for (SlotTransaction transaction : event.getTransactions()) { ItemStack itemStack = transaction.getFinal().createStack(); BigDecimal amount = WalletDrop.getValue(itemStack); if (amount.compareTo(BigDecimal.ZERO) == 0) { continue; } WorldSettings settings = WorldSettings.get(player.getWorld()); if (player.gameMode().get().equals(GameModes.CREATIVE) && !settings.isCreativeModeAllowed()) { event.setCancelled(true); return; } if (settings.isUsePermissions()) { if (!player.hasPermission("walletdrop.enable")) { return; } } WalletPickupEvent moneyPickupEvent = new WalletPickupEvent(itemStack, amount, Cause.of(NamedCause.source(player))); if (!Sponge.getEventManager().post(moneyPickupEvent)) { Sponge.getScheduler() .createTaskBuilder() .delayTicks(2) .execute( c -> { player.getInventory().query(itemStack).clear(); }) .submit(Main.getPlugin()); WalletDrop.depositOrWithdraw(player, moneyPickupEvent.getAmount()); WalletDrop.sendPickupMessage(player, amount); } } }
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException { EntityType entityType = ctx.<EntityType>getOne("mob").get(); if (src instanceof Player) { Player player = (Player) src; ItemStack mobSpawnerStack = ItemStack.builder().itemType(ItemTypes.MOB_SPAWNER).quantity(1).build(); Optional<MobSpawnerData> mobSpawnerData = mobSpawnerStack.getOrCreate(MobSpawnerData.class); if (mobSpawnerData.isPresent()) { MobSpawnerData data = mobSpawnerData.get(); data.nextEntityToSpawn().set(entityType, null); if (mobSpawnerStack.offer(data).isSuccessful()) { player.setItemInHand(mobSpawnerStack); player.sendMessage( Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Created mob spawner.")); } else { player.sendMessage( Text.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Failed to set mob spawner entity.")); } } else { player.sendMessage( Text.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Failed to create mob spawner.")); } } else { src.sendMessage( Text.of( TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /mobspawner!")); } return CommandResult.success(); }
private void checkLoginStatus(Cancellable event, Player player) { if (plugin.getConfigManager().getConfig().isCommandOnlyProtection()) { // check if the user is already registered if (plugin.getDatabase().getAccountIfPresent(player) == null && player.hasPermission(plugin.getContainer().getId() + ".registerRequired")) { event.setCancelled(true); } } else if (!plugin.getDatabase().isLoggedin(player)) { event.setCancelled(true); } }
@Listener public void onDamageEntity(final DamageEntityEvent event) { if (!(event.getTargetEntity() instanceof Player)) { return; } Optional<EntityDamageSource> optionalSource = event.getCause().first(EntityDamageSource.class); if (!optionalSource.isPresent()) { return; } Player attacker = null; if (optionalSource.get().getSource() instanceof Player) { attacker = (Player) optionalSource.get().getSource(); } else if (optionalSource.get() instanceof IndirectEntityDamageSource) { Entity source = ((IndirectEntityDamageSource) optionalSource.get()).getIndirectSource(); if (source instanceof Player) { attacker = (Player) source; } } if (attacker == null) { return; } Player victim = (Player) event.getTargetEntity(); List<Zone> zones = SafeGuard.getZoneManager().getZones(victim.getLocation()); if (zones.isEmpty()) { return; } for (Zone zone : zones) { if (!zone.allows(attacker, pvpFlag)) { attacker.sendMessage(Format.error("Victim is protected from damage by a zone.")); event.setCancelled(true); break; } } }