Java Code Examples for org.bukkit.entity.Player

The following examples show how to use org.bukkit.entity.Player. These examples are extracted from open source projects. 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
@Test
public void testHasUnlocked() throws InterruptedException {
    SlimefunPlugin.getRegistry().setResearchingEnabled(true);

    Player player = server.addPlayer();
    PlayerProfile profile = TestUtilities.awaitProfile(player);

    NamespacedKey key = new NamespacedKey(plugin, "player_profile_test");
    Research research = new Research(key, 280, "Test", 100);
    research.register();

    profile.setResearched(research, true);

    Assertions.assertTrue(profile.hasUnlocked(research));
    Assertions.assertTrue(profile.hasUnlocked(null));

    profile.setResearched(research, false);
    Assertions.assertFalse(profile.hasUnlocked(research));

    // Researches are disabled now, so this method should pass
    // Whether Research#isEnabled() works correctly is covered elsewhere
    SlimefunPlugin.getRegistry().setResearchingEnabled(false);
    Assertions.assertTrue(profile.hasUnlocked(research));
}
 
Example 2
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void onToggleFlight(FlyStatusChangeEvent e) {
    if(!e.getValue()) return;
    
    FileConfiguration config = this.expansion.getConfig("cheat-prevention.yml");
    if (!config.getBoolean("flight.prevent-flying")) return;
    
    IUser affectedUser = e.getAffected();
    Player player = affectedUser.getBase();
    ICombatManager manager = this.plugin.getCombatManager();
    if (!manager.isInCombat(player)) return;
    
    e.setCancelled(true);
    String message = this.plugin.getLanguageMessageColoredWithPrefix("cheat-prevention.flight.no-flying");
    this.plugin.sendMessage(player, message);
}
 
Example 3
Source Project: BungeePerms   Source File: Injector.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Field getPermField(CommandSender sender)
{
    Field perm = null;
    try
    {
        if (sender instanceof Player)
        {
            perm = Class.forName(getVersionedClassName("entity.CraftHumanEntity")).getDeclaredField("perm");
        }
        else if (sender instanceof ConsoleCommandSender)
        {
            perm = Class.forName(getVersionedClassName("command.ServerCommandSender")).getDeclaredField("perm");
        }
    }
    catch (Exception e)
    {
        BungeePerms.getInstance().getDebug().log(e);
    }
    return perm;
}
 
Example 4
Source Project: WildernessTp   Source File: Checks.java    License: MIT License 6 votes vote down vote up
public double getSolidBlock(int x, int z, Player target) {
    if(target.getWorld().getBiome(target.getLocation().getBlockX(),target.getLocation().getBlockZ()).equals(Biome.valueOf(nether)))
        return getSolidBlockNether(x,z,target);
    if (wild.getConfig().getBoolean("Worlds."+target.getWorld().getName()+".InvertY",false))
        return invertSearch(x,z,target);
    else {
        if(target.getWorld().getBiome(x,z).equals(Biome.valueOf(nether)))
            return getSolidBlockNether(x,z,target);
        else {
            /*for (int i = target.getWorld().getMaxHeight(); i >=0; i--) {
                if (!target.getWorld().getBlockAt(x, i, z).isEmpty() && target.getWorld().getBlockAt(x, i + 1, z).isEmpty()
                        && target.getWorld().getBlockAt(x, i + 2, z).isEmpty()
                        && target.getWorld().getBlockAt(x, i + 3, z).isEmpty()
                        && !checkBlocks(target, x, i, z)) {
                    target.sendMessage(ChatColor.LIGHT_PURPLE+ ""+i);
                    return i ;
                }
            }*/
            return target.getWorld().getHighestBlockYAt(x,z);
            //return (target.getWorld().getHighestBlockAt(x,z).getY()-1)+5;
        }

    }
    //return 10;
}
 
Example 5
@Override
public void execute(CommandSender sender, String[] args) throws Exception {
	Player player = (Player) sender;
	NovaPlayer nPlayer = PlayerManager.getPlayer(sender);

	if(!nPlayer.hasGuild()) {
		Message.CHAT_GUILD_NOTINGUILD.send(sender);
		return;
	}

	if(nPlayer.getPreferences().isCompassPointingGuild()) { //disable
		nPlayer.getPreferences().setCompassPointingGuild(false);
		player.setCompassTarget(player.getWorld().getSpawnLocation());
		Message.CHAT_GUILD_COMPASSTARGET_OFF.send(sender);
	}
	else { //enable
		nPlayer.getPreferences().setCompassPointingGuild(true);
		player.setCompassTarget(nPlayer.getGuild().getHome());
		Message.CHAT_GUILD_COMPASSTARGET_ON.send(sender);
	}
}
 
Example 6
Source Project: XSeries   Source File: Titles.java    License: MIT License 6 votes vote down vote up
/**
 * Clears the title and subtitle message from the player's screen.
 *
 * @param player the player to clear the title from.
 * @since 1.0.0
 */
public static void clearTitle(@Nonnull Player player) {
    Objects.requireNonNull(player, "Cannot clear title from null player");
    if (supported) {
        player.resetTitle();
        return;
    }
    Object clearPacket = null;

    try {
        clearPacket = PACKET.invoke(CLEAR, null, -1, -1, -1);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }

    ReflectionUtils.sendPacket(player, clearPacket);
}
 
Example 7
Source Project: Civs   Source File: CivilianManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
Civilian createDefaultCivilian(UUID uuid) {
    ConfigManager configManager = ConfigManager.getInstance();
    CivClass defaultClass = ClassManager.getInstance().createDefaultClass(uuid);
    Set<CivClass> classes = new HashSet<>();
    classes.add(defaultClass);
    int expOrbs = -1;
    if (Civs.getInstance() != null) {
        Player player = Bukkit.getPlayer(uuid);
        if (player != null) {
            expOrbs = player.getTotalExperience();
        }
    }
    Civilian civilian = new Civilian(uuid,
            configManager.getDefaultLanguage(),
            new HashMap<>(),
            classes,
            new HashMap<>(), 0, 0, 0, 0, 0, 0, expOrbs);
    civilian.getStashItems().putAll(ItemManager.getInstance().getNewItems(civilian));
    civilian.setTutorialPath("default");
    civilian.setTutorialIndex(0);
    civilian.setUseAnnouncements(true);
    civilian.setTutorialProgress(0);
    return civilian;
}
 
Example 8
Source Project: AdditionsAPI   Source File: EntityShootCustomBow.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityShootCustomBowLowest(EntityShootCustomBowEvent customEvent) {
	if (customEvent.isCancelled())
		return;

	CustomBow cBow = customEvent.getCustomBow();

	if (!(cBow.getPermissions() instanceof BowPermissions))
		return;
	BowPermissions perm = (BowPermissions) cBow.getPermissions();

	EntityShootBowEvent event = customEvent.getEntityShootBowEvent();

	if (event.getEntity().getType().equals(EntityType.PLAYER)
			&& !PermissionUtils.allowedAction((Player) event.getEntity(), perm.getType(), perm.getShoot()))
		event.setCancelled(true);
}
 
Example 9
@Test
public void shouldNotBypassBecauseBypassDisabled() {
    // given
    Player player = mock(Player.class);
    given(player.getName()).willReturn("Bob");
    given(player.getGameMode()).willReturn(GameMode.SURVIVAL);
    Group from = mockGroup("test_group", GameMode.SURVIVAL, true);
    Group to = mockGroup("other_group", GameMode.SURVIVAL, true);
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(true);

    // when
    process.processWorldChange(player, from, to);

    // then
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example 10
private void clearInventory(Player player, CommandSender sender)
{
	InventoryClearEvent clearEvent = new InventoryClearEvent(player, sender);
	Bukkit.getPluginManager().callEvent(clearEvent);
	if(clearEvent.isCancelled()) return;
	player.getInventory().clear();
	if(sender.equals(player))
	{
		messageOwnInventoryCleared.send(player);
		Bukkit.getPluginManager().callEvent(new InventoryClearedEvent(player, sender));
	}
	else
	{
		messageInventoryWasCleared.send(player, sender.getName(), (sender instanceof Player) ? ((Player) sender).getDisplayName() : ChatColor.GRAY + sender.getName());
		messageOtherInventoryCleared.send(sender, player.getName(), player.getDisplayName());
		Bukkit.getPluginManager().callEvent(new InventoryClearedEvent(player, sender));
	}
}
 
Example 11
Source Project: Slimefun4   Source File: MagicSugar.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public ItemUseHandler getItemHandler() {
    return e -> {
        // Check if it is being placed into an ancient altar.
        if (e.getClickedBlock().isPresent()) {
            Material block = e.getClickedBlock().get().getType();

            if (block == Material.DISPENSER || block == Material.ENCHANTING_TABLE) {
                return;
            }
        }

        Player p = e.getPlayer();
        if (p.getGameMode() != GameMode.CREATIVE) {
            ItemUtils.consumeItem(e.getItem(), false);
        }

        p.playSound(p.getLocation(), Sound.ENTITY_GENERIC_EAT, 1, 1);
        p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 600, 3));
    };
}
 
Example 12
Source Project: civcraft   Source File: Attack.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onAttack(EntityDamageByEntityEvent event, ItemStack inHand) {
	AttributeUtil attrs = new AttributeUtil(inHand);
	double dmg = this.getDouble("value");
			
	double extraAtt = 0.0;
	for (LoreEnhancement enh : attrs.getEnhancements()) {
		if (enh instanceof LoreEnhancementAttack) {
			extraAtt +=  ((LoreEnhancementAttack)enh).getExtraAttack(attrs);
		}
	}
	dmg += extraAtt;
	
	if (event.getDamager() instanceof Player) {
		Resident resident = CivGlobal.getResident(((Player)event.getDamager()));
		if (!resident.hasTechForItem(inHand)) {
			dmg = dmg / 2;
		}
	}
	
	if (dmg < 0.5) {
		dmg = 0.5;
	}
	
	event.setDamage(dmg);
}
 
Example 13
/**
 * Opens a menu loaded by ChestCommands to a player.
 * NOTE: this method ignores permissions.
 *
 * @param player   - the player that will see the GUI.
 * @param yamlFile - the file name of the menu to open. The .yml extension CANNOT be omitted.
 * @return true - if the menu was found and opened, false if not.
 */
public static boolean openPluginMenu(Player player, String yamlFile) {
	IconMenu menu = ChestCommands.getFileNameToMenuMap().get(yamlFile);

	if (menu != null) {
		menu.open(player);
		return true;
	} else {
		return false;
	}
}
 
Example 14
Source Project: Kettle   Source File: CraftServer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Player getPlayer(UUID id) {
    EntityPlayerMP player = playerList.getPlayerByUUID(id);

    if (player != null) {
        return player.getBukkitEntity();
    }

    return null;
}
 
Example 15
Source Project: RedProtect   Source File: ListCommand.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
    if (args.length == 1 && RedProtect.get().ph.hasPerm(sender, "redprotect.command.admin.list")) {
        if (args[0].isEmpty())
            return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
        else
            return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(p -> p.toLowerCase().startsWith(args[0].toLowerCase())).collect(Collectors.toList());
    }
    return new ArrayList<>();
}
 
Example 16
Source Project: TAB   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Player[] getOnlinePlayers(){
	try {
		Object players = Bukkit.class.getMethod("getOnlinePlayers").invoke(null);
		if (players instanceof Player[]) {
			//1.5.x - 1.6.x
			return (Player[]) players;
		} else {
			//1.7+
			return ((Collection<Player>)players).toArray(new Player[0]); 
		}
	} catch (Exception e) {
		return Shared.errorManager.printError(new Player[0], "Failed to get online players");
	}
}
 
Example 17
@Test
public void shouldHandleExceptionWhenRemovingLimbo() {
    // given
    Player player = mock(Player.class);
    Logger logger = TestHelper.setupLogger();
    LimboPersistenceHandler handler = getHandler();
    doThrow(UnsupportedOperationException.class).when(handler).removeLimboPlayer(player);

    // when
    limboPersistence.removeLimboPlayer(player);

    // then
    verify(logger).warning(argThat(containsString("[UnsupportedOperationException]")));
}
 
Example 18
Source Project: TradePlus   Source File: TradePlus.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Trade getTrade(Player player1, Player player2) {
  for (Trade trade : ongoingTrades) {
    if (trade.player1.equals(player1) && trade.player2.equals(player2)) return trade;
    if (trade.player2.equals(player1) && trade.player1.equals(player2)) return trade;
  }
  return null;
}
 
Example 19
@Override
public void onPacketSending(PacketEvent event)
{
	if (!event.isCancelled())
	{
		Player player = event.getPlayer();
		if (!player.isValid()) //Work around, getIfPresent is broken inside WG due to using LocalPlayer as key instead of CacheKey
		{
			return;
		}

		try
		{
			Session session = WorldGuardExtraFlagsPlugin.getPlugin().getWorldGuardCommunicator().getSessionManager().get(player);
			
			GiveEffectsFlagHandler giveEffectsHandler = session.getHandler(GiveEffectsFlagHandler.class);
			if (giveEffectsHandler.isSupressRemovePotionPacket())
			{
				event.setCancelled(true);
			}
		}
		catch(IllegalStateException wgBug)
		{
			
		}
	}
}
 
Example 20
Source Project: EliteMobs   Source File: CombatTag.java    License: GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
    public void onDamage(EntityDamageByEntityEvent event) {

        Player player = playerFinder(event);

        if (player == null) return;

        if (player.getGameMode().equals(GameMode.CREATIVE)) return;

        if (player.isInvulnerable()) player.setInvulnerable(false);
        if (player.isFlying()) {
            player.setFlying(false);
            player.spigot().sendMessage(ChatMessageType.ACTION_BAR,
                    TextComponent.fromLegacyText(ChatColorConverter.convert(ConfigValues.combatTagConfig.getString(CombatTagConfig.COMBAT_TAG_MESSAGE))));
            new BukkitRunnable() {
                @Override
                public void run() {
                    //TODO: introduce the featherfall potion effect for versions above 1.12.2
//                    if (NameHandler.currentVersionIsUnder(13, 0)) {
                    if (!player.isOnline() || player.isDead())
                        cancel();
                    if (player.isOnGround()) {
                        player.setFallDistance(0F);
                        cancel();
                    }
//                    } else {
////TODO: introduce the featherfall potion effect for versions above 1.12.2
//                        if (!player.isOnline() || player.isDead())
//                            player.removePotionEffect(PotionEffectType.SLOW);
//                            cancel();
//                        if (player.isOnGround()) {
//                            player.setFallDistance(0F);
//                            cancel();
//                        }
//
//                    }
                }
            }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1);
        }
    }
 
Example 21
Source Project: ServerTutorial   Source File: ViewConversation.java    License: MIT License 5 votes vote down vote up
@Override
public Prompt getNextPrompt(ConversationContext context) {
    Player player = (Player) context.getForWhom();
    String location = ServerTutorial.getInstance().getServer().getPlayer(player.getName()).getLocation()
            .getWorld().getName() + "," + ServerTutorial.getInstance().getServer().getPlayer(player.getName()
    ).getLocation().getX() + "," + ServerTutorial.getInstance().getServer().getPlayer(player.getName())
            .getLocation().getY() + "," + ServerTutorial.getInstance().getServer().getPlayer(player.getName()
    ).getLocation().getZ() + "," + ServerTutorial.getInstance().getServer().getPlayer(player.getName())
            .getLocation().getYaw() + "," + ServerTutorial.getInstance().getServer().getPlayer(player.getName
            ()).getLocation().getPitch();
    String message = context.getSessionData("message").toString();
    String messageType = context.getSessionData("messagetype").toString();
    String name = context.getSessionData("name").toString();
    String viewTime = context.getSessionData("viewtime").toString();
    int viewID = 1;
    while (DataLoading.getDataLoading().getData().get("tutorials." + context.getSessionData("name") + ".views" +
            "." + viewID) != null) {
        viewID++;
    }
    try {
        DataLoading.getDataLoading().getData().set("tutorials." + name + ".views." + viewID + ".message",
                message);
        DataLoading.getDataLoading().getData().set("tutorials." + name + ".views." + viewID + ".messagetype",
                messageType);
        DataLoading.getDataLoading().getData().set("tutorials." + name + ".views." + viewID + ".location",
                location);
        DataLoading.getDataLoading().getData().set("tutorials." + name + ".views." + viewID + ".viewtime", viewTime);
        DataLoading.getDataLoading().saveData();
        Caching.getCaching().reCasheTutorials();
    } catch (Exception e) {
        e.printStackTrace();
    }
    AddViewEvent event = new AddViewEvent(player, TutorialManager.getManager().getTutorial(name),
            TutorialManager.getManager().getTutorialView(name, viewID));
    ServerTutorial.getInstance().getServer().getPluginManager().callEvent(event);
    return END_OF_CONVERSATION;
}
 
Example 22
Source Project: FunnyGuilds   Source File: ExecutorCaller.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
    if (!(sender instanceof Player)) {
        return Collections.emptyList();
    }
    
    if (this.secondary != null) {
        return Arrays.asList(this.secondary);
    } else {
        return null;
    }
}
 
Example 23
Source Project: KTP   Source File: UHPluginListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onEntityRegainHealth(final EntityRegainHealthEvent ev) {
	if (ev.getRegainReason() == RegainReason.SATIATED) ev.setCancelled(true);
	if (ev.getEntity() instanceof Player) {
		Bukkit.getScheduler().runTaskLater(this.p, new BukkitRunnable() {
			
			@Override
			public void run() {
				p.updatePlayerListName((Player)ev.getEntity());
			}
		}, 1L);
	}
}
 
Example 24
Source Project: uSkyBlock   Source File: uSkyBlock.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean playerIsInSpawn(Player player) {
    Location pLoc = player.getLocation();
    if (!getWorldManager().isSkyWorld(pLoc.getWorld())) {
        return false;
    }
    Location spawnCenter = new Location(WorldManager.skyBlockWorld, 0, pLoc.getBlockY(), 0);
    return spawnCenter.distance(pLoc) <= Settings.general_spawnSize;
}
 
Example 25
Source Project: SonarPet   Source File: Pet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows(CancelledSpawnException.class)
public Pet(Player owner)  {
    Objects.requireNonNull(owner, "Null owner");
    this.ownerId = Objects.requireNonNull(owner.getUniqueId());
    this.petType = this.determinePetType();
    this.setPetName(petType.getDefaultName(owner.getName()));
    spawnPet(getOwner(), getPetType().getPrimaryHookType(), false);
}
 
Example 26
Source Project: FunnyGuilds   Source File: IndividualPrefixManager.java    License: Apache License 2.0 5 votes vote down vote up
public static void addPlayer(String player) {
    for (Player p : Bukkit.getOnlinePlayers()) {
        IndividualPrefix prefix = User.get(p).getCache().getIndividualPrefix();

        if (prefix == null) {
            continue;
        }

        prefix.addPlayer(player);
    }
    
    updatePlayers();
}
 
Example 27
Source Project: skRayFall   Source File: EffNameOfScore.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] exp, int arg1, Kleenean arg2, ParseResult arg3) {
    players = (Expression<Player>) exp[0];
    name = (Expression<String>) exp[1];
    return true;
}
 
Example 28
@Override
public void execute(@NotNull final CommandSender sender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String[] args)
{
	MarriagePlayer player = getMarriagePlugin().getPlayerData((Player) sender);
	if(player.getOpenRequest() != null)
	{
		player.getOpenRequest().deny(player);
	}
	else
	{
		messageNothingToDeny.send(sender);
	}
}
 
Example 29
Source Project: BetonQuest   Source File: PlaysoundEvent.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    Player player = PlayerConverter.getPlayer(playerID);
    if (location != null) {
        player.playSound(location.getLocation(playerID), sound, soundCategoty, volume, pitch);
    } else {
        player.playSound(player.getLocation(), sound, soundCategoty, volume, pitch);
    }
    return null;
}
 
Example 30
@EventHandler
public void onPickup(EntityPickupItemEvent event) {
    if (!(event.getEntity() instanceof Player)) {
        return;
    }

    PlayerListener.onItemPickup((Player) event.getEntity(), event.getItem(), event);
}