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
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 attackwhile(randomTarget == i) randomTarget = (int)(Math.random()*fighters.size()); //if the target is yourself, find a new targetfighters.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 +
- '}';
- }
- }
import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class FighterTest { private Random mockRandom = Mockito.mock(Random.class); @Test void fighter_cannot_be_created_with_negative_health() { assertThrows(IllegalArgumentException.class, () -> { new Fighter("Mateusz", 10, -1); }); } @Test void fighter_cannot_be_created_with_negative_strength() { assertThrows(IllegalArgumentException.class, () -> { new Fighter("Mateusz", -100, 10); }); } @Test void health_reduced_after_hit() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(20); assertEquals(80, mateusz.getHealth()); } @Test void fighter_alive_when_health_is_above_zero_after_hit() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(30); assertFalse(mateusz.isDead()); } @Test void fighter_dies_when_health_reaches_zero() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(100); assertTrue(mateusz.isDead()); } @Test void fighter_dies_when_health_is_below_zero() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(200); assertTrue(mateusz.isDead()); } @Test void alive_health_status() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(20); assertEquals("Mateusz's health left: 80", mateusz.healthStatus()); } @Test void dead_health_status() { Fighter mateusz = new Fighter("Mateusz", 10, 100); mateusz.reduceHealth(120); assertEquals("MATEUSZ IS DEAD!", mateusz.healthStatus()); } @Test void target_health_updated_during_attack() { Fighter mateusz = new Fighter("Mateusz", 10, 100, mockRandom); Fighter enemy = new Fighter("Enemy", 10, 100); // random damage formula = (random.nextInt(strength)/2) + (strength/2); // random damage = (60 / 2) + (10 / 2) = 35 Mockito.when(mockRandom.nextInt(Mockito.anyInt())).thenReturn(60); mateusz.attack(enemy); assertEquals(65, enemy.getHealth()); } @Test void enemy_dies() { Fighter mateusz = new Fighter("Mateusz", 10, 100, mockRandom); Fighter enemy = new Fighter("Enemy", 10, 55); // random damage formula = (random.nextInt(strength)/2) + (strength/2); // random damage = (100 / 2) + (10 / 2) = 55 Mockito.when(mockRandom.nextInt(Mockito.anyInt())).thenReturn(100); mateusz.attack(enemy); assertTrue(enemy.isDead()); } } class Arena { @Test void arena_1() { Fight fight = new Fight(); fight.addFighter("Mateusz",10,100); fight.addFighter("Your Mom",5,75); fight.addFighter("Pickle Rick",20,110); fight.start(); } @Test void arena_2(){ Fight fight = new Fight(); fight.addFighter("Matimateoki",10,50); fight.addFighter("Your Mom6969",10,50); fight.start(); } @Test void arena_3() { Fight fight = new Fight(); Fighter mateusz = new Fighter("Mateusz",10,100); Fighter yourMom = new Fighter("Your Mom",5,75); Fighter pickleRick = new Fighter("Pickle Rick",20,110); fight.addFighter(mateusz); fight.addFighter(yourMom); fight.addFighter(pickleRick); fight.start(); } @Test void arena_4(){ Fight fight = new Fight(); Fighter matimateoki = new Fighter("Matimateoki",10,50); Fighter yourMom = new Fighter("Your Mom6969",10,50); fight.addFighter(matimateoki); fight.addFighter(yourMom); fight.start(); } }
- import org.junit.jupiter.api.Test;
- import org.mockito.Mockito;
- import java.util.Random;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.jupiter.api.Assertions.assertFalse;
- import static org.junit.jupiter.api.Assertions.assertThrows;
- import static org.junit.jupiter.api.Assertions.assertTrue;
- class FighterTest {
- private Random mockRandom = Mockito.mock(Random.class);
- @Test
- void fighter_cannot_be_created_with_negative_health() {
- assertThrows(IllegalArgumentException.class, () -> {
- new Fighter("Mateusz", 10, -1);
- });
- }
- @Test
- void fighter_cannot_be_created_with_negative_strength() {
- assertThrows(IllegalArgumentException.class, () -> {
- new Fighter("Mateusz", -100, 10);
- });
- }
- @Test
- void health_reduced_after_hit() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(20);
- assertEquals(80, mateusz.getHealth());
- }
- @Test
- void fighter_alive_when_health_is_above_zero_after_hit() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(30);
- assertFalse(mateusz.isDead());
- }
- @Test
- void fighter_dies_when_health_reaches_zero() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(100);
- assertTrue(mateusz.isDead());
- }
- @Test
- void fighter_dies_when_health_is_below_zero() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(200);
- assertTrue(mateusz.isDead());
- }
- @Test
- void alive_health_status() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(20);
- assertEquals("Mateusz's health left: 80", mateusz.healthStatus());
- }
- @Test
- void dead_health_status() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100);
- mateusz.reduceHealth(120);
- assertEquals("MATEUSZ IS DEAD!", mateusz.healthStatus());
- }
class Fight_1 {- @Test
public void arena_1() {Fight fight = new Fight();// do your magic here!- void target_health_updated_during_attack() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100, mockRandom);
- Fighter enemy = new Fighter("Enemy", 10, 100);
fight.introduceYourself("Mateusz",10,100);fight.introduceYourself("Your Mom",5,75);fight.introduceYourself("Pickle Rick",20,110);- // random damage formula = (random.nextInt(strength)/2) + (strength/2);
- // random damage = (60 / 2) + (10 / 2) = 35
- Mockito.when(mockRandom.nextInt(Mockito.anyInt())).thenReturn(60);
fight.startFight();- mateusz.attack(enemy);
- assertEquals(65, enemy.getHealth());
- }
- @Test
public void arena_2(){Fight fight = new Fight();fight.introduceYourself("Matimateoki",10,50);fight.introduceYourself("Your Mom6969",10,50);fight.startFight();- void enemy_dies() {
- Fighter mateusz = new Fighter("Mateusz", 10, 100, mockRandom);
- Fighter enemy = new Fighter("Enemy", 10, 55);
- // random damage formula = (random.nextInt(strength)/2) + (strength/2);
- // random damage = (100 / 2) + (10 / 2) = 55
- Mockito.when(mockRandom.nextInt(Mockito.anyInt())).thenReturn(100);
- mateusz.attack(enemy);
- assertTrue(enemy.isDead());
- }
- }
- class Arena {
- @Test
- void arena_1() {
- Fight fight = new Fight();
- fight.addFighter("Mateusz",10,100);
- fight.addFighter("Your Mom",5,75);
- fight.addFighter("Pickle Rick",20,110);
- fight.start();
- }
- @Test
- void arena_2(){
- Fight fight = new Fight();
- fight.addFighter("Matimateoki",10,50);
- fight.addFighter("Your Mom6969",10,50);
- fight.start();
- }
- @Test
- void arena_3() {
- Fight fight = new Fight();
- Fighter mateusz = new Fighter("Mateusz",10,100);
- Fighter yourMom = new Fighter("Your Mom",5,75);
- Fighter pickleRick = new Fighter("Pickle Rick",20,110);
- fight.addFighter(mateusz);
- fight.addFighter(yourMom);
- fight.addFighter(pickleRick);
- fight.start();
- }
- @Test
- void arena_4(){
- Fight fight = new Fight();
- Fighter matimateoki = new Fighter("Matimateoki",10,50);
- Fighter yourMom = new Fighter("Your Mom6969",10,50);
- fight.addFighter(matimateoki);
- fight.addFighter(yourMom);
- fight.start();
- }
- }
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);
- }
- }
- }
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; class KumiteTest { @Test void sample() { assertTrue(Kumite.hasThree(354523)); assertTrue(Kumite.hasThree(-354523)); assertTrue(Kumite.hasThree(748504231)); assertFalse(Kumite.hasThree(525458)); assertFalse(Kumite.hasThree(-525458)); assertFalse(Kumite.hasThree(2222)); } }
- import static org.junit.jupiter.api.Assertions.assertTrue;
- import static org.junit.jupiter.api.Assertions.assertFalse;
- import org.junit.jupiter.api.Test;
- class KumiteTest {
- @Test
- void sample() {
- assertTrue(Kumite.hasThree(354523));
- assertTrue(Kumite.hasThree(-354523));
- assertTrue(Kumite.hasThree(748504231));
- assertFalse(Kumite.hasThree(525458));
- assertFalse(Kumite.hasThree(-525458));
- assertFalse(Kumite.hasThree(2222));
- }
- }