我想制作一个插件,它可以计算玩家的生命。例如,每个玩家有3条生命。每当他死时,他就会丧命1。当他的生命达到0时,他就被禁止了。
我的方法看起来像这样
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--;
}
}
}
问题是,每当玩家死亡时,该消息始终显示相同的变量“ 3”。该如何解决?
答案 0 :(得分:1)
您必须为每个玩家节省生命。
尝试使用HashMap
例如:
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);
}
}
HashMap允许您为每个键保存一个值。在这种情况下,每位玩家的生命计数。