Ad

Fighter class:

  • Added lots of tests for the logic

  • Let's not allow a fighter to be created with <= 0 health or strength

  • Instead of calculating isDead() every time, let's store it as a boolean field dead in the Fighter class and set it to true as soon as the fighter's health reaches 0

  • Let's use a method to reduce the health of the target fighter

  • Let's use the Random class rather than Math.random for 2 reasons: (1) it has better performance (2) We can inject it as a dependency to have control over our tests

Fight class:

  • Let's ensure there are at least 2 fighters in the arena before starting a fight

  • It's not advisable to delete elements from a list while iterating over it, so using a Queue we can just keep using the first fighter in the queue and then adding them back to the end of the queue after their turn

  • Also since we are polling the queue, we can choose the opponent randomly from the remaining active fighters in the queue rather than having to choose randomly but then check we haven't chosen the current fighter as the opponent

Code
Diff
  • import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Random;
    
    class Fight {
    
        private Random random;
        private Queue<Fighter> nextFighter = new LinkedList<>();
    
        public Fight() {
            this(new Random());
        }
    
        public Fight(Random random) {
            this.random = random;
        }
    
        public void addFighter(String name, int strength, int health) {
            addFighter(new Fighter(name, strength, health));
        }
    
        public void addFighter(Fighter fighter) {
            nextFighter.add(fighter);
            fighter.printIntroduction();
        }
    
        public Fighter start() {
            if (nextFighter.size() < 2) {
                throw new IllegalStateException(String.format("The fight needs at least 2 fighters to start but there are only %d", nextFighter.size()));
            }
    
            System.out.println("\n** The battle begins! **\n");
            while (nextFighter.size() > 1) {
                Fighter attacker = nextFighter.poll();
                Fighter opponent = getRandomOpponent();
                launchAttack(attacker, opponent);
            }
    
            Fighter winner = nextFighter.poll();
            System.out.println(String.format("\n%s is the CHAMPIOOOONNNNN!!!", winner.getName()));
            return winner;
        }
    
        public void launchAttack(Fighter attacker, Fighter opponent) {
            attacker.attack(opponent);
            if (opponent.isDead()) {
                nextFighter.remove(opponent);
            }
            nextFighter.add(attacker);
        }
    
        public Fighter getRandomOpponent() {
            List<Fighter> availableOpponents = new ArrayList<>(nextFighter);
            int randomTarget = random.nextInt(availableOpponents.size());
            return availableOpponents.get(randomTarget);
        }
    
    }
    
    class Fighter {
        private String name;
        private int strength;
        private int health;
        private boolean dead;
        private Random random;
    
        public Fighter(String name, int strength, int health) {
            this(name, strength, health, new Random());
        }
    
        public Fighter(String name, int strength, int health, Random random) {
            if (strength <= 0) {
                throw new IllegalArgumentException(String.format("Strength must be greater than 0, was %d", strength));
            }
            if (health <= 0) {
                throw new IllegalArgumentException(String.format("Health must be greater than 0, was %d", health));
            }
            this.name = name;
            this.strength = strength;
            this.health = health;
            this.dead = false;
            this.random = random;
        }
    
        public boolean isDead() {
            return dead;
        }
    
        public String getName() {
            return name;
        }
    
        public int getHealth() {
            return health;
        }
    
        public void attack(Fighter target) {
            int randomDamage = (random.nextInt(strength)/2) + (strength/2);
            target.reduceHealth(randomDamage);
            String attack = String.format("%s was attacked by %s for %d damage!", target.getName(), name, randomDamage);
            System.out.println(attack);
            System.out.println(target.healthStatus());
        }
    
        public void printIntroduction() {
            String introduction = String.format("Hi, my name is %s (Strength: %d, Health: %d)", name, strength, health);
            System.out.println(introduction);
        }
    
        public void reduceHealth(int damage) {
            health -= damage;
            if (health <= 0) {
                dead = true;
            }
        }
    
        public String healthStatus() {
            if (dead) {
                return String.format("%s IS DEAD!", name.toUpperCase());
            } else {
                return String.format("%s's health left: %d", name, health);
            }
        }
    
        @Override
        public String toString() {
            return "Fighter{" +
                    "name='" + name + '\'' +
                    ", strength=" + strength +
                    ", health=" + health +
                    ", dead=" + dead +
                    '}';
        }
    }
    • import java.util.List;
    • import java.util.ArrayList;
    • import java.util.LinkedList;
    • import java.util.List;
    • import java.util.Queue;
    • import java.util.Random;
    • public class Main {
    • public static void main(String[] args) {
    • //put the battle in testing so that it is print to log
    • }
    • }
    • class Fight {
    • private Random random;
    • private Queue<Fighter> nextFighter = new LinkedList<>();
    • public Fight() {
    • this(new Random());
    • }
    • public Fight(Random random) {
    • this.random = random;
    • }
    • public void addFighter(String name, int strength, int health) {
    • addFighter(new Fighter(name, strength, health));
    • }
    • public void addFighter(Fighter fighter) {
    • nextFighter.add(fighter);
    • fighter.printIntroduction();
    • }
    • public Fighter start() {
    • if (nextFighter.size() < 2) {
    • throw new IllegalStateException(String.format("The fight needs at least 2 fighters to start but there are only %d", nextFighter.size()));
    • }
    • System.out.println("\n** The battle begins! **\n");
    • while (nextFighter.size() > 1) {
    • Fighter attacker = nextFighter.poll();
    • Fighter opponent = getRandomOpponent();
    • launchAttack(attacker, opponent);
    • }
    • Fighter winner = nextFighter.poll();
    • System.out.println(String.format("\n%s is the CHAMPIOOOONNNNN!!!", winner.getName()));
    • return winner;
    • }
    • public void launchAttack(Fighter attacker, Fighter opponent) {
    • attacker.attack(opponent);
    • if (opponent.isDead()) {
    • nextFighter.remove(opponent);
    • }
    • nextFighter.add(attacker);
    • }
    • public Fighter getRandomOpponent() {
    • List<Fighter> availableOpponents = new ArrayList<>(nextFighter);
    • int randomTarget = random.nextInt(availableOpponents.size());
    • return availableOpponents.get(randomTarget);
    • }
    • class Fight {
    • // do your magic here!
    • List<Fighter> fighters = new ArrayList<Fighter>();
    • public void introduceYourself(String name, int strength, int health) {
    • System.out.println("Hi, my name is " + name + " (Strength: " + strength + ", Health: " + health + ")");
    • fighters.add(new Fighter(name,strength,health));
    • }
    • public void startFight(){
    • System.out.println("\n** The battle begins! **\n");
    • while(fighters.size()>1){
    • for(int i=0;i<fighters.size();i++){
    • int randomTarget = (int)(Math.random()*fighters.size()); //gets a random targets position in the list to attack
    • while(randomTarget == i) randomTarget = (int)(Math.random()*fighters.size()); //if the target is yourself, find a new target
    • fighters.get(i).attack(fighters.get(randomTarget));
    • if(fighters.get(randomTarget).isDead()){
    • fighters.remove(randomTarget); //remove target from fighters list if they are dead
    • }
    • }
    • }
    • System.out.println("\n" + fighters.get(0).getName() + " is the CHAMPIOOOONNNNN!!!");
    • }
    • }
    • class Fighter {
    • private String name;
    • private int strength;
    • private int health;
    • public Fighter(String name, int strength, int health){
    • this.name = name;
    • this.strength = strength;
    • this.health = health;
    • }
    • public boolean isDead(){
    • return health <= 0;
    • }
    • public void attack(Fighter target){
    • int randomDamage = (int) ((Math.random() * strength)/2)+(strength/2);
    • target.health -= randomDamage;
    • System.out.println(target.name + " was attacked by " + name + " for "+ randomDamage + " damage! " + ((target.health > 0) ? "("+target.name+"'s health left " + target.health +")" : target.name.toUpperCase() + " HAS DIED!\n"));
    • }
    • public String getName(){
    • return name;
    • }
    • private String name;
    • private int strength;
    • private int health;
    • private boolean dead;
    • private Random random;
    • public Fighter(String name, int strength, int health) {
    • this(name, strength, health, new Random());
    • }
    • public Fighter(String name, int strength, int health, Random random) {
    • if (strength <= 0) {
    • throw new IllegalArgumentException(String.format("Strength must be greater than 0, was %d", strength));
    • }
    • if (health <= 0) {
    • throw new IllegalArgumentException(String.format("Health must be greater than 0, was %d", health));
    • }
    • this.name = name;
    • this.strength = strength;
    • this.health = health;
    • this.dead = false;
    • this.random = random;
    • }
    • public boolean isDead() {
    • return dead;
    • }
    • public String getName() {
    • return name;
    • }
    • public int getHealth() {
    • return health;
    • }
    • public void attack(Fighter target) {
    • int randomDamage = (random.nextInt(strength)/2) + (strength/2);
    • target.reduceHealth(randomDamage);
    • String attack = String.format("%s was attacked by %s for %d damage!", target.getName(), name, randomDamage);
    • System.out.println(attack);
    • System.out.println(target.healthStatus());
    • }
    • public void printIntroduction() {
    • String introduction = String.format("Hi, my name is %s (Strength: %d, Health: %d)", name, strength, health);
    • System.out.println(introduction);
    • }
    • public void reduceHealth(int damage) {
    • health -= damage;
    • if (health <= 0) {
    • dead = true;
    • }
    • }
    • public String healthStatus() {
    • if (dead) {
    • return String.format("%s IS DEAD!", name.toUpperCase());
    • } else {
    • return String.format("%s's health left: %d", name, health);
    • }
    • }
    • @Override
    • public String toString() {
    • return "Fighter{" +
    • "name='" + name + '\'' +
    • ", strength=" + strength +
    • ", health=" + health +
    • ", dead=" + dead +
    • '}';
    • }
    • }
Code
Diff
  • interface Kumite {
      static boolean hasThree(int x) {
        if (x < 0) {
          return hasThree(x * -1);
        } else if (x % 10 == 3) {
          return true;
        } else if (x < 10) {
          return false;
        } else {
          return hasThree(x / 10);
        }
      }
    }
    • interface Kumite {
    • static boolean hasThree(int x) {
    • return ("" + x).indexOf('3') != -1;
    • if (x < 0) {
    • return hasThree(x * -1);
    • } else if (x % 10 == 3) {
    • return true;
    • } else if (x < 10) {
    • return false;
    • } else {
    • return hasThree(x / 10);
    • }
    • }
    • }