Search code examples
javapluginsminecraftbukkit

Spigot Plugin Development - Subtract variable when player dies


I would like to make plugin, that counts player's lives. For example every player has 3 lives. Whenever he dies, he lost 1 life. When he reach 0 lives, he gets banned.

My method looks like this

public class OnPlayerDeath implements Listener {

    private int lives = 3;

    @EventHandler
    public void OnDeath(PlayerDeathEvent event){
        Player player = event.getEntity().getPlayer();
        if (!(player.getKiller() instanceof Player)) 
            player.sendMessage("Died by a something else. You have " + lives + " lives left.");
        else {
            player.sendMessage("Died by a human. You have " + lives + " lives left.");
            lives--;
        }
    }
}

The problem is, whenever player dies, the message shows all the time same variable "3". How to fix that?


Solution

  • You will have to save the amount of lives for each player.

    Try using a HashMap

    For instance:

    public class OnPlayerDeath implements Listener {
    
    // Make new HashMap
    private Map<Player, Integer> livesMap = new HashMap<>();
    
    @EventHandler
    public void OnDeath(PlayerDeathEvent event){
        Player player = event.getEntity().getPlayer();
    
        int lives;
    
        if(!livesMap.containsKey(player)) {
            // Set the default amount of lives to 2. (3 minus 1, since the player already died once)
            lives = 2;
        } else {
            // Subtract one from the player's lives
            lives = livesMap.get(player) - 1;  
        }
    
        if (!(player.getKiller() instanceof Player)) {
            player.sendMessage("Died by a something else. You have " + lives + " lives left.");
        } else {
            player.sendMessage("Died by a human. You have " + lives + " lives left.");
        }
    
        // Update new life count
        livesMap.put(player, lives);
    }
    

    }

    A HashMap allows you to save a value for each key. In this case the life count for each player.