Java Code Examples for org.bukkit.event.entity.PlayerDeathEvent#getEntity()

The following examples show how to use org.bukkit.event.entity.PlayerDeathEvent#getEntity() . 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: PlayerDeathListener.java    From PerWorldInventory with GNU General Public License v3.0 7 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Group group = groupManager.getGroupFromWorld(player.getLocation().getWorld().getName());

    if (!event.getKeepInventory()) {
        player.getInventory().clear();
    }

    if (!event.getKeepLevel()) {
        player.setExp(event.getNewExp());
        player.setLevel(event.getNewLevel());
    }

    player.setFoodLevel(20);
    player.setSaturation(5f);
    player.setExhaustion(0f);
    player.setFallDistance(0f);
    player.setFireTicks(0);
    for (PotionEffect effect : player.getActivePotionEffects()) {
        player.removePotionEffect(effect.getType());
    }

    playerManager.addPlayer(player, group);
}
 
Example 2
Source File: PlayerDeathListener.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
  public void onDeath2(final PlayerDeathEvent v2) {
      final GameMap gameMap = MatchManager.get().getPlayerMap(v2.getEntity());

      if (gameMap == null) {
          return;
      }
       
      final Player player = v2.getEntity();
      v2.getEntity().getInventory().clear();
      v2.getEntity().getInventory().setArmorContents(null);
      
      DamageCause damageCause = DamageCause.CUSTOM;
if (v2.getEntity().getLastDamageCause() != null) {
	damageCause = v2.getEntity().getLastDamageCause().getCause();
} 
final DamageCause dCause = damageCause;
v2.setDeathMessage("");

      MatchManager.get().playerLeave(player, dCause, false, true, true);
  }
 
Example 3
Source File: DropOnDeath.java    From Minepacks with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDeath(PlayerDeathEvent event)
{
	if(honorKeepOnDeath && event.getKeepInventory()) return;
	final Player player = event.getEntity();
	if(plugin.isDisabled(player) != WorldBlacklistMode.None) return;
	if (!player.hasPermission(Permissions.KEEP_ON_DEATH))
	{
		final Location location = player.getLocation();
		plugin.getBackpack(player, new Callback<Backpack>()
		{
			@Override
			public void onResult(Backpack backpack)
			{
				backpack.drop(location);
			}

			@Override
			public void onFail() {}
		});
	}
}
 
Example 4
Source File: HeadDropsModule.java    From UHC with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void on(PlayerDeathEvent event) {
    if (!isEnabled() || RANDOM.nextDouble() < (1D - dropRate)) {
        // set to an empty map to avoid stale metadata problems
        event.getEntity().setMetadata(StandItemsMetadata.KEY, new StandItemsMetadata(plugin));
        return;
    }

    final Player player = event.getEntity();

    // create a head
    final ItemStack head = playerHeadProvider.getPlayerHeadItem(player);

    // add it to the drops
    event.getDrops().add(head);

    // add metadata for the armour stand module to put the helmet on the player and remove from drops
    final EnumMap<EquipmentSlot, ItemStack> standItems = Maps.newEnumMap(EquipmentSlot.class);
    standItems.put(EquipmentSlot.HEAD, head);

    player.setMetadata(StandItemsMetadata.KEY, new StandItemsMetadata(plugin, standItems));
}
 
Example 5
Source File: DeathpointListener.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onDeath(PlayerDeathEvent e) {
    Player p = e.getEntity();

    if (SlimefunUtils.containsSimilarItem(p.getInventory(), SlimefunItems.GPS_EMERGENCY_TRANSMITTER, true)) {
        SlimefunPlugin.getGPSNetwork().addWaypoint(p, "player:death " + SlimefunPlugin.getLocalization().getMessage(p, "gps.deathpoint").replace("%date%", format.format(LocalDateTime.now())), p.getLocation().getBlock().getLocation());
    }
}
 
Example 6
Source File: Blitz.java    From CardinalPGM with MIT License 5 votes vote down vote up
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Optional<TeamModule> team = Teams.getTeamByPlayer(player);
    if (team.isPresent() && !team.get().isObserver()) {
        int oldMeta = this.getLives(player);
        player.removeMetadata("lives", Cardinal.getInstance());
        player.setMetadata("lives", new LazyMetadataValue(Cardinal.getInstance(), LazyMetadataValue.CacheStrategy.NEVER_CACHE, new BlitzLives(oldMeta - 1)));
        if (this.getLives(player) == 0) {
            Teams.getTeamById("observers").get().add(player, true, false);
            player.removeMetadata("lives", Cardinal.getInstance());
        }
    }
}
 
Example 7
Source File: PGMListener.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void clearActiveEnderPearls(final PlayerDeathEvent event) {
    for(Entity entity : event.getEntity().getWorld().getEntitiesByClass(EnderPearl.class)) {
        if(((EnderPearl) entity).getShooter() == event.getEntity()) {
            entity.remove();
        }
    }
}
 
Example 8
Source File: StatsListener.java    From ScoreboardStats with MIT License 5 votes vote down vote up
/**
 * Tracks player deaths and kills
 *
 * @param deathEvent the death event.
 */
@EventHandler
public void onDeath(PlayerDeathEvent deathEvent) {
    Player killed = deathEvent.getEntity();
    //killer is null if it's not a player
    Player killer = killed.getKiller();
    if (killed.equals(killer)) {
        return;
    }

    if (Settings.isActiveWorld(killed.getWorld().getName())) {
        ReplaceManager replaceManager = ReplaceManager.getInstance();

        database.getStats(killed).ifPresent(killedCache -> {
            killedCache.onDeath();
            replaceManager.forceUpdate(killed, "deaths", killedCache.getDeaths());
            replaceManager.forceUpdate(killed, "kdr", killedCache.getKdr());
            //will reset
            replaceManager.forceUpdate(killed, "current_streak", killedCache.getCurrentStreak());
        });


        database.getStats(killer).ifPresent(killercache -> {
            killercache.onKill();
            replaceManager.forceUpdate(killer, "kills", killercache.getKills());
            replaceManager.forceUpdate(killer, "kdr", killercache.getKdr());
            //maybe the player reaches a new high score
            replaceManager.forceUpdate(killer, "killstreak", killercache.getKillstreak());
            replaceManager.forceUpdate(killer, "current_streak", killercache.getCurrentStreak());
        });
    }
}
 
Example 9
Source File: DeathContext.java    From UHC with MIT License 5 votes vote down vote up
public DeathContext(PlayerDeathEvent event) {
    this.original = event.getDeathMessage();
    this.player = new PlayerWrapper(event.getEntity());

    final Player potentialKiller = event.getEntity().getKiller();
    this.killer = potentialKiller == null ? null : new PlayerWrapper(potentialKiller);
}
 
Example 10
Source File: ArmorListener.java    From AdditionsAPI with MIT License 5 votes vote down vote up
@EventHandler
public void playerDeathEvent(PlayerDeathEvent e){
	Player p = e.getEntity();
	for(ItemStack i : p.getInventory().getArmorContents()){
		if(!isAirOrNull(i)){
			Bukkit.getServer().getPluginManager().callEvent(new ArmorEquipEvent(p, EquipMethod.DEATH, ArmorType.matchType(i), i, null));
			// No way to cancel a death event.
		}
	}
}
 
Example 11
Source File: PetOwnerListener.java    From SonarPet with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Player p = event.getEntity();
    IPet pet = EchoPet.getManager().getPet(p);
    if (pet != null) {
        EchoPet.getManager().saveFileData("autosave", pet);
        EchoPet.getSqlManager().saveToDatabase(pet, false);
        EchoPet.getManager().removePet(pet, true);
        //p.sendMessage(Lang.REMOVE_PET_DEATH.toString());
    }
}
 
Example 12
Source File: UCListener.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onDeath(PlayerDeathEvent e) {
    Player p = e.getEntity();
    if (UChat.get().getUCJDA() != null && !p.hasPermission(UChat.get().getUCConfig().getString("discord.vanish-perm"))) {
        Bukkit.getScheduler().runTaskAsynchronously(UChat.get(), () ->
                UChat.get().getUCJDA().sendRawToDiscord(UChat.get().getLang().get("discord.death").replace("{player}", p.getName())));
    }
}
 
Example 13
Source File: PlayerListener.java    From WorldGuardExtraFlagsPlugin with MIT License 5 votes vote down vote up
@EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event)
{
	Player player = event.getEntity();
	
	ApplicableRegionSet regions = this.plugin.getWorldGuardCommunicator().getRegionContainer().createQuery().getApplicableRegions(player.getLocation());
	
	Boolean keepInventory = WorldGuardUtils.queryValue(player, player.getWorld(), regions.getRegions(), Flags.KEEP_INVENTORY);
	if (keepInventory != null)
	{
		event.setKeepInventory(keepInventory);
		
		if (keepInventory)
		{
			event.getDrops().clear();
		}
	}
	
	Boolean keepExp = WorldGuardUtils.queryValue(player, player.getWorld(), regions.getRegions(), Flags.KEEP_EXP);
	if (keepExp != null)
	{
		event.setKeepLevel(keepExp);

		if (keepExp)
		{
			event.setDroppedExp(0);
		}
	}
}
 
Example 14
Source File: GameListeners.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void deathHandler(PlayerDeathEvent event)
{
	final Player player = event.getEntity();
	final AnniPlayer p = AnniPlayer.getPlayer(player.getUniqueId());
	if(p != null)
		p.getKit().cleanup(player);
}
 
Example 15
Source File: GameListeners.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void DeathListener(PlayerDeathEvent event)
{
	String message = "";
	Player player = event.getEntity();
	Player killer = player.getKiller();
	
	if(Game.isGameRunning())
	{
		AnniPlayer p = AnniPlayer.getPlayer(player.getUniqueId());
		if(p != null)
		{
			if(killer != null)
			{
				AnniPlayer k = AnniPlayer.getPlayer(killer.getUniqueId());
				if(k != null)
				{
					PlayerKilledEvent e = new PlayerKilledEvent(k,p);//TODO--------This should be created earlier, then the message should be based off of attributes computed by the event
					
					message = p.getTeam().getColor()+player.getName()+"("+p.getKit().getName()+") "+Lang.DEATHPHRASE.toString()+" "+k.getTeam().getColor()+killer.getName()+"("+k.getKit().getName()+")";
					
					if(e.getAttributes().contains(KillAttribute.REMEMBRANCE))
						message += " "+Lang.REMEMBRANCE.toString();
					else if(e.getAttributes().contains(KillAttribute.NEXUSDEFENSE))
						message += " "+Lang.NEXUSKILL.toString();
						
					AnniEvent.callEvent(e);
					if(!e.shouldDropXP())
						event.setDroppedExp(0);
				}	
			}
			else 
				event.setDroppedExp(0);
			event.setDeathMessage(message);
		}
	}
}
 
Example 16
Source File: DeathListener.java    From ViaVersion with MIT License 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onDeath(PlayerDeathEvent e) {
    Player p = e.getEntity();
    if (isOnPipe(p) && Via.getConfig().isShowNewDeathMessages() && checkGamerule(p.getWorld()) && e.getDeathMessage() != null)
        sendPacket(p, e.getDeathMessage());
}
 
Example 17
Source File: DeathsListener.java    From Statz with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDie(final PlayerDeathEvent event) {

	final PlayerStat stat = PlayerStat.DEATHS;

	// Get player
	final Player player = event.getEntity();

	// Do general check
	if (!plugin.doGeneralCheck(player, stat))
		return;

	PlayerStatSpecification specification = new DeathsSpecification(player.getUniqueId(), 1,
			player.getWorld().getName());


	// Update value to new stat.
	plugin.getDataManager().setPlayerInfo(player.getUniqueId(), stat, specification.constructQuery());

}
 
Example 18
Source File: PlayerDeathListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDeath(PlayerDeathEvent event){
	Player player = event.getEntity();
	GameManager gm = GameManager.getGameManager();
	PlayersManager pm = gm.getPlayersManager();
	MainConfiguration cfg = gm.getConfiguration();
	UhcPlayer uhcPlayer = pm.getUhcPlayer(player);

	if (uhcPlayer.getState() != PlayerState.PLAYING){
		Bukkit.getLogger().warning("[UhcCore] " + player.getName() + " died while already in 'DEAD' mode!");
		player.kickPlayer("Don't cheat!");
		return;
	}

	pm.setLastDeathTime();

	// kill event
	Player killer = player.getKiller();
	if(killer != null){
		UhcPlayer uhcKiller = pm.getUhcPlayer(killer);

		uhcKiller.kills++;

		// Call Bukkit event
		UhcPlayerKillEvent killEvent = new UhcPlayerKillEvent(uhcPlayer, uhcKiller);
		Bukkit.getServer().getPluginManager().callEvent(killEvent);

		if(cfg.getEnableKillEvent()){
			double reward = cfg.getRewardKillEvent();
			List<String> killCommands = cfg.getKillCommands();
			if (reward > 0) {
				VaultManager.addMoney(killer, reward);
				if (!Lang.EVENT_KILL_REWARD.isEmpty()) {
					killer.sendMessage(Lang.EVENT_KILL_REWARD.replace("%money%", "" + reward));
				}
			}
			// If the list is empty, this will never execute
			killCommands.forEach(cmd -> {
				try {
					Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("%name%", uhcKiller.getRealName()));
				} catch (CommandException exception){
					Bukkit.getLogger().warning("[UhcCore] Failed to execute kill reward command: " + cmd);
					exception.printStackTrace();
				}
			});
		}
	}

	// Store drops in case player gets re-spawned.
	uhcPlayer.getStoredItems().clear();
	uhcPlayer.getStoredItems().addAll(event.getDrops());

	// eliminations
	ScenarioManager sm = gm.getScenarioManager();
	if (!sm.isActivated(Scenario.SILENTNIGHT) || !((SilentNightListener) sm.getScenarioListener(Scenario.SILENTNIGHT)).isNightMode()) {
		gm.broadcastInfoMessage(Lang.PLAYERS_ELIMINATED.replace("%player%", player.getName()));
	}

	if(cfg.getRegenHeadDropOnPlayerDeath()){
		event.getDrops().add(UhcItems.createRegenHead(uhcPlayer));
	}

	if(cfg.getEnableGoldenHeads()){
		if (cfg.getPlaceHeadOnFence() && !gm.getScenarioManager().isActivated(Scenario.TIMEBOMB)){
			// place head on fence
			Location loc = player.getLocation().clone().add(1,0,0);
			loc.getBlock().setType(UniversalMaterial.OAK_FENCE.getType());
			loc.add(0, 1, 0);
			loc.getBlock().setType(UniversalMaterial.PLAYER_HEAD_BLOCK.getType());

			Skull skull = (Skull) loc.getBlock().getState();
			VersionUtils.getVersionUtils().setSkullOwner(skull, uhcPlayer);
			skull.setRotation(BlockFace.NORTH);
			skull.update();
		}else{
			event.getDrops().add(UhcItems.createGoldenHeadPlayerSkull(player.getName(), player.getUniqueId()));
		}
	}

	if(cfg.getEnableExpDropOnDeath()){
		UhcItems.spawnExtraXp(player.getLocation(), cfg.getExpDropOnDeath());
	}

	uhcPlayer.setState(PlayerState.DEAD);
	pm.strikeLightning(uhcPlayer);
	pm.playSoundPlayerDeath();

	// handle player leaving the server
	boolean canContinueToSpectate = player.hasPermission("uhc-core.spectate.override")
			|| cfg.getCanSpectateAfterDeath();

	if (!canContinueToSpectate) {
		if (cfg.getEnableBungeeSupport()) {
			Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), new TimeBeforeSendBungeeThread(uhcPlayer, cfg.getTimeBeforeSendBungeeAfterDeath()));
		} else {
			player.kickPlayer(Lang.DISPLAY_MESSAGE_PREFIX + " " + Lang.KICK_DEAD);
		}
	}

	pm.checkIfRemainingPlayers();
}
 
Example 19
Source File: ItemListener.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
	if (event.getKeepInventory()) {
		return;
	}

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

	if (!MineTinker.getPlugin().getConfig().getBoolean("ItemBehaviour.ApplyOnPlayerDeath", true)) { //For DeadSouls and other Grave-Plugins
		// TODO: Try to find better handling of this Event or with these Plugins
		return;
	}

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

		boolean isMineTinker = false;

		if (MineTinker.getPlugin().getConfig().getBoolean("ItemBehaviour.ForModItems")) { //Modifieritems
			ItemStack modifierTester = itemStack.clone();
			modifierTester.setAmount(1);

			for (Modifier modifier : modManager.getAllowedMods()) {
				if (modifier.getModItem().equals(modifierTester)) {
					isMineTinker = true;
					break;
				}
			}
		}

		if (modManager.isArmorViable(itemStack) || modManager.isToolViable(itemStack) || modManager.isWandViable(itemStack)) {
			isMineTinker = true;
		}

		if (!isMineTinker) {
			continue;
		}

		if (!MineTinker.getPlugin().getConfig().getBoolean("ItemBehaviour.DisableDroppingBehaviour")) {
			PlayerDropItemEvent dropItemEvent = new PlayerDropItemEvent(player, player.getWorld().dropItem(player.getLocation(), itemStack));
			Bukkit.getPluginManager().callEvent(dropItemEvent); //To trigger item behaviour
			itemStack.setAmount(0);
		}
	}
}
 
Example 20
Source File: PlayerDeath.java    From ZombieEscape with GNU General Public License v2.0 4 votes vote down vote up
@EventHandler
public void onDeath(PlayerDeathEvent event) {
    event.setDeathMessage(null);
    event.getDrops().clear();
    event.setDroppedExp(0);
    final Player player = event.getEntity();
    player.setHealth(20); // Do not show the respawn screen
    player.getInventory().clear();

    final GameArena gameArena = PLUGIN.getGameArena();

    if (!gameArena.isGameRunning()) {
        player.teleport(PLUGIN.getServerSpawn());
        return;
    }

    if (gameArena.isHuman(player)) {
        gameArena.addZombie(player);
        player.getInventory().setHelmet(new ItemStack(Material.JACK_O_LANTERN));
        gameArena.giveKit(player);

        if (player.getKiller() != null) {
            Profile zombieProfile = PLUGIN.getProfile(player.getKiller());
            if (zombieProfile != null) {
                zombieProfile.setHumanKills(zombieProfile.getHumanKills() + 1);
            }
        }
    } else if (gameArena.isZombie(player)) {
        new BukkitRunnable() {
            @Override
            public void run() {
                gameArena.teleportCheckpoint(player);
                gameArena.giveKit(player);
                player.setFireTicks(0);
                player.setHealth(20);
            }
        }.runTaskLater(PLUGIN, 10);
    }

    if (gameArena.isGameRunning()) {
        if (gameArena.shouldEnd()) {
            gameArena.endGame();
        }
    }
}