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

The following examples show how to use org.bukkit.entity.Player#canSee() . 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: Command.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
private List<String> tabComplete0(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException {
    Validate.notNull(sender, "Sender cannot be null");
    Validate.notNull(args, "Arguments cannot be null");
    Validate.notNull(alias, "Alias cannot be null");

    if (args.length == 0) {
        return ImmutableList.of();
    }

    String lastWord = args[args.length - 1];

    Player senderPlayer = sender instanceof Player ? (Player) sender : null;

    ArrayList<String> matchedPlayers = new ArrayList<String>();
    for (Player player : sender.getServer().getOnlinePlayers()) {
        String name = player.getName();
        if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) {
            matchedPlayers.add(name);
        }
    }

    Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER);
    return matchedPlayers;
}
 
Example 2
Source File: CraftMapRenderer.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void render(MapView map, MapCanvas canvas, Player player) {
    // Map
    for (int x = 0; x < 128; ++x) {
        for (int y = 0; y < 128; ++y) {
            canvas.setPixel(x, y, worldMap.colors[y * 128 + x]);
        }
    }

    // Cursors
    MapCursorCollection cursors = canvas.getCursors();
    while (cursors.size() > 0) {
        cursors.removeCursor(cursors.getCursor(0));
    }

    for (Object key : worldMap.mapDecorations.keySet()) {
        // If this cursor is for a player check visibility with vanish system
        Player other = Bukkit.getPlayerExact((String) key);
        if (other != null && !player.canSee(other)) {
            continue;
        }

        MapDecoration decoration = worldMap.mapDecorations.get(key);
        cursors.addCursor(decoration.getX(), decoration.getY(), (byte) (decoration.getRotation() & 15), decoration.getImage());
    }
}
 
Example 3
Source File: CraftServer.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public List<String> tabCompleteChat(Player player, String message) {
    List<String> completions = new ArrayList<String>();
    PlayerChatTabCompleteEvent event = new PlayerChatTabCompleteEvent(player, message, completions);
    String token = event.getLastToken();
    for (Player p : getOnlinePlayers()) {
        if (player.canSee(p) && StringUtil.startsWithIgnoreCase(p.getName(), token)) {
            completions.add(p.getName());
        }
    }
    pluginManager.callEvent(event);

    Iterator<?> it = completions.iterator();
    while (it.hasNext()) {
        Object current = it.next();
        if (!(current instanceof String)) {
            // Sanity
            it.remove();
        }
    }
    Collections.sort(completions, String.CASE_INSENSITIVE_ORDER);
    return completions;
}
 
Example 4
Source File: FlagInvisibleSpectate.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@Subscribe(priority = Subscribe.Priority.MONITOR)
public void onPlayerJoinGame(PlayerPreJoinGameEvent event) {
	Game game = event.getGame();
	
	if (event.getJoinResult() != JoinResult.ALLOW || game.getGameState() == GameState.INGAME) {
		return;
	}
	
	SpleefPlayer player = event.getPlayer();
	Player bukkitPlayer = player.getBukkitPlayer();
	
	FlagSpectate flag = (FlagSpectate) getParent();
	
	for (SpleefPlayer spectating : flag.getSpectators()) {
		if (!bukkitPlayer.canSee(spectating.getBukkitPlayer())) {
			continue;
		}
		
		bukkitPlayer.hidePlayer(spectating.getBukkitPlayer());
	}
}
 
Example 5
Source File: NameTagChanger.java    From NameTagChanger with MIT License 5 votes vote down vote up
private void updatePlayer(Player player, String oldName) {
    Validate.isTrue(enabled, "NameTagChanger is disabled");
    GameProfileWrapper newProfile = gameProfiles.get(player.getUniqueId());
    if (newProfile == null) {
        newProfile = packetHandler.getDefaultPlayerProfile(player);
    }
    List<Team> scoreboardTeamsToUpdate = Lists.newArrayList();
    sendingPackets = true;
    for (Player otherPlayer : Bukkit.getOnlinePlayers()) {
        if (otherPlayer.equals(player)) {
            if (otherPlayer.getScoreboard().getEntryTeam(player.getName()) != null) {
                scoreboardTeamsToUpdate.add(otherPlayer.getScoreboard().getEntryTeam(player.getName()));
            }
            continue;
        }
        if (otherPlayer.canSee(player)) {
            packetHandler.sendTabListRemovePacket(player, otherPlayer);
            packetHandler.sendTabListAddPacket(player, newProfile, otherPlayer);
            if (otherPlayer.getWorld().equals(player.getWorld())) {
                packetHandler.sendEntityDestroyPacket(player, otherPlayer);
                packetHandler.sendNamedEntitySpawnPacket(player, otherPlayer);
                packetHandler.sendEntityEquipmentPacket(player, otherPlayer);
            }
        }
        // The player we want to rename is in a scoreboard team.
        if (otherPlayer.getScoreboard().getEntryTeam(player.getName()) != null) {
            scoreboardTeamsToUpdate.add(otherPlayer.getScoreboard().getEntryTeam(player.getName()));
        }
    }
    if (oldName != null) {
        String newName = newProfile.getName();
        for (Team team : scoreboardTeamsToUpdate) {
            Bukkit.getOnlinePlayers().stream().filter(p -> p.getScoreboard() == team.getScoreboard()).forEach(p -> {
                packetHandler.sendScoreboardRemovePacket(oldName, p, team.getName());
                packetHandler.sendScoreboardAddPacket(newName, p, team.getName());
            });
        }
    }
    sendingPackets = false;
}
 
Example 6
Source File: PopperGizmo.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler
public void entityDamage(final EntityDamageEvent event) {
    if(!(event instanceof EntityDamageByEntityEvent)) return;
    EntityDamageByEntityEvent realEvent = (EntityDamageByEntityEvent) event;
    if(!(realEvent.getDamager() instanceof Player) || !(realEvent.getEntity() instanceof Player)) return;

    final Player damager = (Player) realEvent.getDamager();
    final Player victim = (Player) realEvent.getEntity();

    if(victim.hasPermission(GizmoConfig.EXEMPT_PERMISSION)) return;

    if(!(Gizmos.gizmoMap.get(damager) instanceof PopperGizmo)) return;
    if(damager.getItemInHand().getType() != this.getIcon()) return;

    if(!damager.canSee(victim)) return;

    damager.hidePlayer(victim);
    damager.playSound(damager.getLocation(), Sound.BLOCK_LAVA_POP, 1f, 2f);

    Integer count = poppedCount.get(damager);
    if(count == null) count = 0;

    count++;
    poppedCount.put(damager, count);

    if(count % 10 == 0) {
        RaindropUtil.giveRaindrops(
            Users.playerId(damager), 1, null,
            new TranslatableComponent("gizmo.popper.raindropsResult", new Component(String.valueOf(count), net.md_5.bungee.api.ChatColor.GOLD))
        );
    }

    event.setCancelled(true);
}
 
Example 7
Source File: PlayerMovementHandler.java    From ClaimChunk with MIT License 5 votes vote down vote up
private void showTitle(Player player, Chunk newChunk) {
    // Get the UUID of the new chunk owner
    UUID newOwner = claimChunk.getChunkHandler().getOwner(newChunk.getWorld(), newChunk.getX(),
            newChunk.getZ());

    // Check if this player doesn't own the new chunk
    if (newOwner != null && !player.getUniqueId().equals(newOwner)) {
        // Get the name of the chunks for the owner of this chunk and display it
        PlayerHandler ph = claimChunk.getPlayerHandler();
        String newName = ph.getChunkName(newOwner);
        String text = ((newName == null)
                ? claimChunk.getMessages().unknownChunkOwner  // Something probably went wrong with the PlayerHandler
                : claimChunk.getMessages().chunkOwner.replace("%%PLAYER%%", newName));
        showTitleRaw(true, player, text);

        // Send a message to the chunk owner if possible
        if (ph.hasAlerts(newOwner)) {
            Player owner = Bukkit.getPlayer(newOwner);
            if (owner != null) {
                if (owner.canSee(player)
                        || !claimChunk.chConfig().getBool("chunks", "hideAlertsForVanishedPlayers")) {
                    showTitleRaw(false, owner, claimChunk.getMessages().playerEnterChunk.replace("%%PLAYER%%", player.getDisplayName()));
                }
            }
        }
    } else {
        // This chunk is owned by this player
        showTitleRaw(true, player, claimChunk.getMessages().chunkSelf);
    }
}
 
Example 8
Source File: CraftMapRenderer.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void render(MapView map, MapCanvas canvas, Player player) {
    if(CauldronCommand.debug) {
    System.out.println("Default Map Render called!");
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        System.out.println(ste);
    } }


    // Map
    for (int x = 0; x < 128; ++x) {
        for (int y = 0; y < 128; ++y) {
            canvas.setPixel(x, y, worldMap.colors[y * 128 + x]);
        }
    }

    // Cursors
    MapCursorCollection cursors = canvas.getCursors();
    while (cursors.size() > 0) {
        cursors.removeCursor(cursors.getCursor(0));
    }

    for (UUID key : worldMap.playersVisibleOnMap.keySet()) { // Spigot string -> uuid
        // If this cursor is for a player check visibility with vanish system
        Player other = Bukkit.getPlayer(key); // Spigot
        if (other != null && !player.canSee(other)) {
            continue;
        }

        net.minecraft.world.storage.MapData.MapCoord decoration = (net.minecraft.world.storage.MapData.MapCoord) worldMap.playersVisibleOnMap.get(key);
        cursors.addCursor(decoration.centerX, decoration.centerZ, (byte) (decoration.iconRotation & 15), decoration.iconSize);
    }
}
 
Example 9
Source File: CraftServer.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public List<String> tabCompleteChat(Player player, String message) {
    List<String> completions = new ArrayList<String>();
    PlayerChatTabCompleteEvent event = new PlayerChatTabCompleteEvent(player, message, completions);
    String token = event.getLastToken();
    for (Player p : getOnlinePlayers()) {
        if (player.canSee(p) && StringUtil.startsWithIgnoreCase(p.getName(), token)) {
        	if (event.isPinging())
        	{
        		StringBuilder sb = new StringBuilder(1 + p.getName().length());
        		sb.append('@'); sb.append(p.getName());
        		completions.add(sb.toString());
        	}
        	else
        		completions.add(p.getName());
        }
    }
    pluginManager.callEvent(event);

    Iterator<?> it = completions.iterator();
    while (it.hasNext()) {
        Object current = it.next();
        if (!(current instanceof String)) {
            // Sanity
            it.remove();
        }
    }
    Collections.sort(completions, String.CASE_INSENSITIVE_ORDER);
    return completions;
}
 
Example 10
Source File: Util.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a list of online players this player can see, i.e. are not invisible
 * @param player
 * @return
 */
public static List<String> getOnlinePlayerList(Player player) {
    final List<String> returned = new ArrayList<String>();
    for (Player p : Bukkit.getServer().getOnlinePlayers()) {
        if (player == null || player.canSee(p)) {
            returned.add(p.getName());
        }
    }
    return returned;
}
 
Example 11
Source File: TpCommand.java    From MarriageMaster with GNU General Public License v3.0 5 votes vote down vote up
public void doTheTP(Player player, Player partner)
{
	if(player.canSee(partner))
	{
		if(!blacklistedWorlds.contains(partner.getLocation().getWorld().getName().toLowerCase()) || player.hasPermission(Permissions.BYPASS_WORLD_BLACKLIST))
		{
			Location loc = partner.getLocation();
			if(safetyCheck && (loc = getSaveLoc(loc)) == null)
			{
				messageUnsafe.send(player);
				messageToUnsafe.send(partner);
			}
			else
			{
				player.teleport(loc);
				messageTeleport.send(player);
				messageTeleportTo.send(partner);
			}
		}
		else
		{
			messageWorldNotAllowed.send(player);
		}
	}
	else
	{
		messagePartnerVanished.send(player);
	}
}
 
Example 12
Source File: PlayerStateHolder.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Applies the default state to the player
 * and discards the current one<br><br>
 * 
 * Warning: This deletes the entire inventory
 * and all other various player attributes
 * 
 * It is recommended to save the player state
 * with {@link PlayerStateHolder#create(Player, GameMode)}
 * and store a reference to it before invoking this method
 * 
 * @param player
 */
public static void applyDefaultState(Player player, boolean adventureMode) {
	player.setGameMode(adventureMode ? GameMode.ADVENTURE : GameMode.SURVIVAL);
	player.getInventory().clear();
	player.getInventory().setArmorContents(new ItemStack[4]);
	player.setItemOnCursor(null);
	player.updateInventory();
       player.setMaxHealth(20.0);
	player.setHealth(20.0);
	player.setFoodLevel(20);
	player.setLevel(0);
	player.setExp(0f);
	player.setAllowFlight(false);
	player.setFlying(false);
	player.setFallDistance(0);
	player.setFireTicks(0);
	
	Collection<PotionEffect> effects = player.getActivePotionEffects();
	for (PotionEffect effect : effects) {
		player.removePotionEffect(effect.getType());
	}
	
	for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
		if (player.canSee(player)) {
			continue;
		}
		
		player.showPlayer(onlinePlayer);
	}
}
 
Example 13
Source File: FlagInvisibleSpectate.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void onPlayerLeaveGame(PlayerLeaveGameEvent event) {
	SpleefPlayer player = event.getPlayer();
	Player bukkitPlayer = player.getBukkitPlayer();
	
	FlagSpectate flag = (FlagSpectate) getParent();
	
	for (SpleefPlayer spectating : flag.getSpectators()) {
		if (bukkitPlayer.canSee(spectating.getBukkitPlayer())) {
			continue;
		}
		
		bukkitPlayer.showPlayer(spectating.getBukkitPlayer());
	}
}
 
Example 14
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);
}