Как получить ключи хэш-карты, которые имеют значение меньше x, в список массивов, чтобы он восстанавливался до значения x каждый раз, когда ключи получают значение меньше x

Я делаю плагин Bukkit, в котором у игроков есть мана и заклинания. У каждого заклинания своя стоимость маны, и игроки начинают с 20 маны.

У меня есть ArrayList, где я храню игроков, у которых меньше 20 маны, и HashMap, где хранится текущая мана игроков. Мне нужно знать, как сделать метод, который будет добавлять 1 ману каждую секунду к игрокам с менее чем 20 маны.

Мне нужно делать это каждый раз, когда игрок попадает в ArrayList, а затем удалять его из списка, когда он достигает 20 маны.

Вот мой текущий код:

public HashMap<String, Integer> mana = new HashMap<String, Integer>();
public ArrayList<String> changedMana = new ArrayList<String>();

public void onManaChange(){
  //code goes here
}

person L3n    schedule 28.03.2015    source источник
comment
Вы можете объяснить свой вопрос просто. Я думаю, что эти mana и spells формулировки немного усложняют вопрос.   -  person ravindrab    schedule 28.03.2015
comment
ну, есть заклинания, которые стоят маны, мана нужна для произнесения заклинаний...   -  person L3n    schedule 28.03.2015


Ответы (2)


Вы можете запускать таймер задачи каждую секунду (это должно быть помещено в ваш метод onEnable()):

Bukkit.getServer().getScheduler().runTaskTimer(plugin, new Runnable(){
    public void run(){

    }
},20L,20L); //run this task every 20 ticks (20 ticks = 1 second)

и добавить ману игрокам, которые находятся в ArrayList:

List<String> toRemove = new ArrayList<String>();

for(String player : changedMana){ //loop through all of the players in the ArrayList
   int current = mana.get(player); //get the player's current mana
   if(current < 20){ //if the player's mana is less than 20
       current++; //add to the player's mana
       mana.put(player, current); //update the player's mana
   }
   else if(current == 20){ //if the player's mana is greater than or equal to 20
       toRemove.add(player); //add the player to the toRemove list, in order to remove the player from the ArrayList later safely
   }
   else{
     //do something if the current mana is > 20, if you don't want to, just remove this
   }
}

changedMana.removeAll(toRemove); //remove players from the changed mana array

Итак, вот как мог бы выглядеть ваш код, если бы он был в вашем классе Main (тот, что extends JavaPlugin):

public HashMap<String, Integer> mana = new HashMap<String, Integer>();
public ArrayList<String> changedMana = new ArrayList<String>();

@Override
public void onEnable(){
  Bukkit.getServer().getScheduler().runTaskTimer(plugin, new Runnable(){
    public void run(){
      List<String> toRemove = new ArrayList<String>();

      for(String player : changedMana){ //loop through all of the players in the ArrayList
        int current = mana.get(player); //get the player's current mana
        if(current < 20){ //if the player's mana is less than 20
           current++; //add to the player's mana
           mana.put(player, current); //update the player's mana
        }
        else if(current == 20){ //if the player's mana is greater than or equal to 20
           toRemove.add(player); //add the player to the toRemove list, in order to remove the player from the ArrayList later safely
        }
        else{
           //do something if the current mana is > 20, if you don't want to, just remove this
        }
      }

      changedMana.removeAll(toRemove); //remove players from the changed mana array
    }
  },20L,20L);
}
person Jojodmo    schedule 29.03.2015

Измените его на TreeMap и используйте headMap() метод.

person user207421    schedule 28.03.2015
comment
Почему? Какая разница? - person L3n; 28.03.2015
comment
TreeMap имеет гарантированный порядок, а HashMap — нет. - person hd1; 29.03.2015
comment
@ L3n Потому что у Treemap есть метод headMap(), а у HashMap нет. - person user207421; 29.03.2015