0

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) {

    }
}
  • https://stackoverflow.com/questions/16252269/how-to-sort-an-arraylist would help you. Then if you have a specific problem, post the sorting code you use and the issue you have. Thanks! – JP Moresmau Jan 12 '19 at 12:54
  • 1
    Where is the `list` of enemies in your code? Also, in your explanation, there were 2 goblins, 1 spider and a player. But your attack plan is player then 3 goblins. Where did this 3rd goblin show up? – YetAnotherBot Jan 12 '19 at 13:13
  • Possible duplicate of [Sort a List of objects by multiple fields](https://stackoverflow.com/questions/6850611/sort-a-list-of-objects-by-multiple-fields) – Nicholas K Jan 12 '19 at 13:25
  • @JamiSaueressig is your issue resolved? – catch23 Jan 24 '19 at 20:31

1 Answers1

1

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.

catch23
  • 17,519
  • 42
  • 144
  • 217