Reputation: 33
Far a game I need two sort an object arraylist (Room.enemies) on the speed attribute and player object with it's speed attribute so I can know in which order I need to run the attack methods.
For example, in the room.enemies array I have a goblin(speed 10) spider(speed 8) goblin(speed 10) and the player has a speed of 12 I would want to execute attack enemy from the player first and then execute the attackplayer method three times (goblin, goblin, goblin).
import java.util.Random;
public class Battle {
private boolean attackPlayer(Player player, Enemy enemy) {
int edamage = 0;
int eamplifier = enemy.getDamage() - player.getDefense();
Random dice = new Random();
for (int i=1; i < enemy.getAgility(); i++) {
edamage += dice.nextInt(10) + eamplifier;
}
if (edamage < 0) {
edamage = 0;
}
return player.takeDamage(edamage);
}
private boolean attackEnemy(Player player, Enemy enemy) {
int damage = 0;
int amplifier = player.getDamage() - enemy.getDefense();
Random dice = new Random();
for (int i=1; i < player.getAgility(); i++) {
damage += dice.nextInt(10) + amplifier;
}
if (damage < 0) {
damage = 0;
}
return enemy.takeDamage(damage);
}
private void gameturn(Player player, Room room) {
}
}
Upvotes: 0
Views: 59
Reputation: 18572
If you are using Java 8 or higher (I hope that it is). You can use convenience Comparators with Stream API.
Something like the following:
ArrayList<String> list = new ArrayList(....);
list.sort(Comparator.comparing(Enemy::getSpeed)
.thenComparing(Enemy::someOtherProperty));
Or just with Stream API usage:
List<String> sortedBySpeed = list.stream()
.sorted(Comparator.comparing(Enemy::getSpeed))
.collect(Collectors.toList());
And you have the list with sorted enemies sortedBySpeed
.
Upvotes: 1