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

The following examples show how to use org.bukkit.entity.Player#getHealth() . 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: PercentHealthObjectiveModule.java    From UHC with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void on(EntityDamageEvent event) {
    final Entity entity = event.getEntity();
    if (!(entity instanceof Player)) {
        return;
    }

    final Player player = (Player) entity;

    // If the event was cancelled, another plugin may have edited the health
    // Update instantly with the current health
    if (event.isCancelled()) {
        updatePlayer(player);
        return;
    }

    // Calculate new health based on final damage instead of waiting for one tick
    final double oldHealth = player.getHealth();
    final double finalDamage = event.getFinalDamage();
    final double newHealth = Math.max(oldHealth - finalDamage, 0);

    updatePlayer(player, newHealth);
}
 
Example 2
Source File: Splint.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ItemUseHandler getItemHandler() {
    return e -> {
        Player p = e.getPlayer();

        // Player is neither burning nor injured
        if (p.getFireTicks() <= 0 && p.getHealth() >= p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()) {
            return;
        }

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

        p.getWorld().playSound(p.getLocation(), Sound.ENTITY_SKELETON_HURT, 1, 1);
        p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 0));

        e.cancel();
    };
}
 
Example 3
Source File: PlayerRespawnRunnable.java    From UHC with MIT License 5 votes vote down vote up
@Override
public void run() {
    final Player toRespawn = this.player.get();

    if (toRespawn == null || toRespawn.getHealth() != 0) return;

    toRespawn.spigot().respawn();
}
 
Example 4
Source File: FullHealthAction.java    From UHC with MIT License 5 votes vote down vote up
@Override
protected void run(Player player) {
    revertHealth = player.getHealth();

    // set to max health
    player.setHealth(player.getMaxHealth());
}
 
Example 5
Source File: Berserker.java    From ce with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void effect(Event e, ItemStack item, int level) {
	EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;
	Player player = (Player) event.getEntity();
	if(player.getHealth() <= trigger) {
		player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, duration * level, strength + level - 1));
		player.sendMessage("Your bloodloss makes you stronger!");
		generateCooldown(player, cooldown);
	}
}
 
Example 6
Source File: Berserker.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void damageListener(final EntityDamageByEntityEvent event)
{
	if(event.getEntity().getType() == EntityType.PLAYER && event.getDamager().getType() == EntityType.PLAYER)
	{
		Player one = (Player)event.getDamager();
		AnniPlayer p = AnniPlayer.getPlayer(one.getUniqueId());
		if(p != null && p.getKit().equals(this))
		{
			if((one.getHealth() / one.getMaxHealth()) <= .42)
				event.setDamage(event.getDamage()+1);
		}
	}
}
 
Example 7
Source File: TheHangingGardens.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onUpdate() {
	super.onUpdate();
	
	for (Town t : this.getTown().getCiv().getTowns()) {
		for (Resident res : t.getResidents()) {
			try {
				Player player = CivGlobal.getPlayer(res);
				
				if (player.isDead() || !player.isValid()) {
					continue;
				}
				
				if (player.getHealth() >= 20) {
					continue;
				}
				
				TownChunk tc = CivGlobal.getTownChunk(player.getLocation());
				if (tc == null || tc.getTown() != this.getTown()) {
					continue;
				}
				
				if (player.getHealth() >= 19.0) {
					player.setHealth(20);
				} else {
					player.setHealth(player.getHealth() + 1);
				}
			} catch (CivException e) {
				//Player not online;
			}
			
		}
	}
}
 
Example 8
Source File: BestPvEListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run(){
    for (UhcPlayer uhcPlayer : GameManager.getGameManager().getPlayersManager().getOnlinePlayingPlayers()){
        Player player;

        try{
            player = uhcPlayer.getPlayer();
        }catch (UhcPlayerNotOnlineException ex){
            continue; // No hp for offline players
        }

        if (!pveList.containsKey(uhcPlayer)){
            pveList.put(uhcPlayer,true); // Should never occur, playing players are always on list.
            Bukkit.getLogger().warning("[UhcCore] " + player.getName() + " was not on best PvE list yet! Please contact a server administrator.");
        }

        if (player.getGameMode().equals(GameMode.SURVIVAL) && pveList.get(uhcPlayer)){
            // heal player
            if (player.getHealth() + 2 > player.getMaxHealth()){
                player.setMaxHealth(player.getMaxHealth() + 2);
            }

            player.setHealth(player.getHealth() + 2);
        }
    }

    taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(UhcCore.getPlugin(),this,delay*TimeUtils.SECOND_TICKS);
}
 
Example 9
Source File: BestPvEListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler (priority = EventPriority.HIGHEST)
public void onPlayerDamage(EntityDamageEvent e){
    if (e.isCancelled()){
        return;
    }

    if (e.getDamage() < 0.2){
        return;
    }

    if (!(e.getEntity() instanceof Player)){
        return;
    }

    Player p = (Player) e.getEntity();
    UhcPlayer uhcPlayer = GameManager.getGameManager().getPlayersManager().getUhcPlayer(p);

    if (!pveList.containsKey(uhcPlayer)){
        return; // Only playing players on list
    }

    if (pveList.get(uhcPlayer)) {
        pveList.put(uhcPlayer, false);
        uhcPlayer.sendMessage(Lang.SCENARIO_BESTPVE_REMOVED);
    }

    if (p.getMaxHealth() > maxHealth){
        double hp = p.getHealth();

        if (hp < maxHealth){
            p.setMaxHealth(maxHealth);
        }else{
            p.setMaxHealth(hp + 1);
        }
    }
}
 
Example 10
Source File: PWIPlayer.java    From PerWorldInventory with GNU General Public License v3.0 5 votes vote down vote up
PWIPlayer(Player player, Group group, double bankBalance, double balance, boolean useAttributes) {
    this.uuid = player.getUniqueId();
    this.name = player.getName();
    this.location = player.getLocation();

    this.group = group;
    this.saved = false;

    this.armor = player.getInventory().getArmorContents();
    this.enderChest = player.getEnderChest().getContents();
    this.inventory = player.getInventory().getContents();

    this.canFly = player.getAllowFlight();
    this.displayName = player.getDisplayName();
    this.exhaustion = player.getExhaustion();
    this.experience = player.getExp();
    this.isFlying = player.isFlying();
    this.foodLevel = player.getFoodLevel();
    if (useAttributes) {
        this.maxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue();
    } else {
        this.maxHealth = player.getMaxHealth();
    }
    this.health = player.getHealth();
    this.gamemode = player.getGameMode();
    this.level = player.getLevel();
    this.saturationLevel = player.getSaturation();
    this.potionEffects = player.getActivePotionEffects();
    this.fallDistance = player.getFallDistance();
    this.fireTicks = player.getFireTicks();
    this.maxAir = player.getMaximumAir();
    this.remainingAir = player.getRemainingAir();

    this.bankBalance = bankBalance;
    this.balance = balance;
}
 
Example 11
Source File: TutorialPlayer.java    From ServerTutorial with MIT License 5 votes vote down vote up
public TutorialPlayer(Player player) {
    this.startLoc = player.getLocation();
    this.inventory = player.getInventory().getContents();
    this.flight = player.isFlying();
    this.allowFlight = player.getAllowFlight();
    this.exp = player.getExp();
    this.level = player.getLevel();
    this.hunger = player.getFoodLevel();
    this.health = player.getHealth();
    this.gameMode = player.getGameMode();
}
 
Example 12
Source File: ViewInventoryMatchModule.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 updateMonitoredHealth(final EntityRegainHealthEvent event) {
    if(event.getEntity() instanceof Player) {
        Player player = (Player) event.getEntity();
        if(player.getHealth() == player.getMaxHealth()) return;
        this.scheduleCheck((Player) event.getEntity());
    }
}
 
Example 13
Source File: Poisonous.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
	if (event.getCause() != EntityDamageEvent.DamageCause.POISON) return;
	if (!(event.getEntity() instanceof Player)) return;
	if (!this.effectHealsPlayer) return;

	Player player = (Player) event.getEntity();
	if (!player.hasPermission("minetinker.modifiers.poisonous.use")) {
		return;
	}

	boolean hasPoisonous = false;
	ItemStack armor = null;
	for (ItemStack stack : player.getInventory().getArmorContents()) {
		if (stack == null) continue;
		if (modManager.hasMod(stack, this)) {
			hasPoisonous = true;
			armor = stack;
			break;
		}
	}

	if (!hasPoisonous) return;

	double damage = event.getDamage();
	if (damage > 0) {
		event.setDamage(0);
		double health = player.getHealth();
		player.setHealth(Math.min(health + damage, player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()));
		ChatWriter.logModifier(player, event, this, armor, String.format("Health(%.2f -> %.2f)", health, player.getHealth()));
	}
}
 
Example 14
Source File: Berserk.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onHit(EntityDamageEvent event) {
	if (!(event.getEntity() instanceof Player)) {
		return;
	}

	Player player = (Player) event.getEntity();

	if (!player.hasPermission("minetinker.modifiers.berserk.use")) {
		return;
	}

	ItemStack chest = player.getInventory().getChestplate();

	if (!modManager.isArmorViable(chest)) {
		return;
	}

	int modifierLevel = modManager.getModLevel(chest, this);

	if (modifierLevel <= 0) {
		return;
	}

	double lifeAfterDamage = player.getHealth() - event.getFinalDamage();
	AttributeInstance healthAttr = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);

	double maxHealth = 20;

	if (healthAttr != null) {
		maxHealth = healthAttr.getValue();
	}

	if (player.getHealth() / maxHealth > trigger / 100.0 && lifeAfterDamage / maxHealth <= trigger / 100.0) {
		player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, boostTime, modifierLevel - 1));
		ChatWriter.logModifier(player, event, this, chest,
				"Time(" + boostTime + ")", "Amplifier(" + (modifierLevel - 1) + ")");
	}
}
 
Example 15
Source File: Withered.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
	if (event.getCause() != EntityDamageEvent.DamageCause.WITHER) return;
	if (!(event.getEntity() instanceof Player)) return;
	if (!this.effectHealsPlayer) return;

	Player player = (Player) event.getEntity();
	if (!player.hasPermission("minetinker.modifiers.withered.use")) {
		return;
	}

	boolean hasWither = false;
	ItemStack armor = null;
	for (ItemStack stack : player.getInventory().getArmorContents()) {
		if (stack == null) continue;
		if (modManager.hasMod(stack, this)) {
			hasWither = true;
			armor = stack;
			break;
		}
	}

	if (!hasWither) return;

	double damage = event.getDamage();
	if (damage > 0) {
		event.setDamage(0);
		double health = player.getHealth();
		player.setHealth(Math.min(health + damage, player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()));
		ChatWriter.logModifier(player, event, this, armor, String.format("Health(%.2f -> %.2f)", health, player.getHealth()));
	}
}
 
Example 16
Source File: DieObjective.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLastDamage(EntityDamageEvent event) {
    if (!cancel) {
        return;
    }
    if (event.getEntity() instanceof Player) {
        final Player player = (Player) event.getEntity();
        final String playerID = PlayerConverter.getID(player);
        if (containsPlayer(playerID) && player.getHealth() - event.getFinalDamage() <= 0
                && checkConditions(playerID)) {
            event.setCancelled(true);
            player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
            player.setFoodLevel(20);
            player.setExhaustion(4);
            player.setSaturation(20);
            for (PotionEffect effect : player.getActivePotionEffects()) {
                player.removePotionEffect(effect.getType());
            }
            if (location != null) {
                try {
                    player.teleport(location.getLocation(playerID));
                } catch (QuestRuntimeException e) {
                    LogUtils.getLogger().log(Level.SEVERE, "Couldn't execute onLastDamage in DieObjective");
                    LogUtils.logThrowable(e);
                }
            }
            new BukkitRunnable() {
                @Override
                public void run() {
                    player.setFireTicks(0);

                }
            }.runTaskLater(BetonQuest.getInstance(), 1);
            completeObjective(playerID);
        }
    }
}
 
Example 17
Source File: ViewInventoryMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void updateMonitoredHealth(final EntityRegainHealthEvent event) {
  if (event.getEntity() instanceof Player) {
    Player player = (Player) event.getEntity();
    if (player.getHealth() == player.getMaxHealth()) return;
    this.scheduleCheck((Player) event.getEntity());
  }
}
 
Example 18
Source File: VeinMinerListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onBlockBreak(BlockBreakEvent e){
    Player player = e.getPlayer();

    if (!player.isSneaking()){
        return;
    }

    Block block = e.getBlock();
    ItemStack tool = player.getItemInHand();

    if (block.getType() == UniversalMaterial.GLOWING_REDSTONE_ORE.getType()){
        block.setType(Material.REDSTONE_ORE);
    }

    if (!UniversalMaterial.isCorrectTool(block.getType(), player.getItemInHand().getType())){
        return;
    }

    // find all surrounding blocks
    Vein vein = new Vein(block);
    vein.process();

    player.getWorld().dropItem(player.getLocation().getBlock().getLocation().add(.5,.5,.5), vein.getDrops(getVeinMultiplier(vein.getDropType())));

    if (vein.getTotalXp() != 0){
        UhcItems.spawnExtraXp(player.getLocation(), vein.getTotalXp());
    }

    // Process blood diamonds.
    if (isActivated(Scenario.BLOODDIAMONDS) && vein.getDropType() == Material.DIAMOND){
        player.getWorld().playSound(player.getLocation(), UniversalSound.PLAYER_HURT.getSound(), 1, 1);

        if (player.getHealth() < vein.getOres()){
            player.setHealth(0);
        }else {
            player.setHealth(player.getHealth() - vein.getOres());
        }
    }

    int newDurability = tool.getDurability()-vein.getOres();
    if (newDurability<1) newDurability = 1;

    tool.setDurability((short) newDurability);
    player.setItemInHand(tool);
}
 
Example 19
Source File: Lifesteal.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) //because of Melting
public void effect(MTEntityDamageByEntityEvent event) {
	if (event.getPlayer().equals(event.getEvent().getEntity())) {
		return; //when event was triggered by the armor
	}

	Player player = event.getPlayer();
	ItemStack tool = event.getTool();

	if (!player.hasPermission("minetinker.modifiers.lifesteal.use")) {
		return;
	}

	if (!modManager.hasMod(tool, this)) {
		return;
	}

	Random rand = new Random();
	int n = rand.nextInt(100);

	if (n > this.percentToTrigger) {
		ChatWriter.logModifier(player, event, this, tool, String.format("Chance(%d/%d)", n, this.percentToTrigger));
		return;
	}

	int level = modManager.getModLevel(tool, this);
	double damage = event.getEvent().getDamage();
	double recovery = damage * ((percentPerLevel * level) / 100.0);
	double health = player.getHealth() + recovery;

	AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);

	if (attribute != null) {
		// for IllegalArgumentExeption if Health is biggen than MaxHealth
		if (health > attribute.getValue()) {
			health = attribute.getValue();
		}

		player.setHealth(health);
	}

	ChatWriter.logModifier(player, event, this, tool, String.format("Chance(%d/%d)", n, this.percentToTrigger),
			String.format("HealthGain(%.2f [%.2f/%.2f = %.4f])", recovery, recovery, damage, recovery/damage));
}
 
Example 20
Source File: DPlayerData.java    From DungeonsXL with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Saves the player's data to the file.
 *
 * @param player the Player to save
 */
public void savePlayerState(Player player) {
    oldGameMode = player.getGameMode();
    oldFireTicks = player.getFireTicks();
    oldFoodLevel = player.getFoodLevel();
    if (is1_9) {
        oldMaxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue();
    }
    oldHealth = player.getHealth();
    oldExp = player.getExp();
    oldLvl = player.getLevel();
    oldArmor = new ArrayList<>(Arrays.asList(player.getInventory().getArmorContents()));
    oldInventory = new ArrayList<>(Arrays.asList(player.getInventory().getContents()));
    if (is1_9) {
        oldOffHand = player.getInventory().getItemInOffHand();
    }
    oldLocation = player.getLocation();
    oldPotionEffects = player.getActivePotionEffects();
    if (is1_9) {
        oldCollidabilityState = player.isCollidable();
        oldInvulnerabilityState = player.isInvulnerable();
    }
    oldFlyingState = player.getAllowFlight();

    config.set(PREFIX_STATE_PERSISTENCE + "oldGameMode", oldGameMode.toString());
    config.set(PREFIX_STATE_PERSISTENCE + "oldFireTicks", oldFireTicks);
    config.set(PREFIX_STATE_PERSISTENCE + "oldFoodLevel", oldFoodLevel);
    config.set(PREFIX_STATE_PERSISTENCE + "oldMaxHealth", oldMaxHealth);
    config.set(PREFIX_STATE_PERSISTENCE + "oldHealth", oldHealth);
    config.set(PREFIX_STATE_PERSISTENCE + "oldExp", oldExp);
    config.set(PREFIX_STATE_PERSISTENCE + "oldLvl", oldLvl);
    config.set(PREFIX_STATE_PERSISTENCE + "oldArmor", oldArmor);
    config.set(PREFIX_STATE_PERSISTENCE + "oldInventory", oldInventory);
    config.set(PREFIX_STATE_PERSISTENCE + "oldOffHand", oldOffHand);
    config.set(PREFIX_STATE_PERSISTENCE + "oldLocation", oldLocation);
    config.set(PREFIX_STATE_PERSISTENCE + "oldPotionEffects", oldPotionEffects);
    config.set(PREFIX_STATE_PERSISTENCE + "oldCollidabilityState", oldCollidabilityState);
    config.set(PREFIX_STATE_PERSISTENCE + "oldFlyingState", oldFlyingState);
    config.set(PREFIX_STATE_PERSISTENCE + "oldInvulnerabilityState", oldInvulnerabilityState);

    save();
}