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

    }
}
4
  • 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! Commented Jan 12, 2019 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? Commented Jan 12, 2019 at 13:13
  • Possible duplicate of Sort a List of objects by multiple fields Commented Jan 12, 2019 at 13:25
  • @JamiSaueressig is your issue resolved? Commented Jan 24, 2019 at 20:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.