Skip to content

Commit c9502f0

Browse files
author
Tony Brar
committed
Handle when Characters have no Weapon or target
Uses a default Weapon of "fists" Skips attack if no target is picked
1 parent f81151c commit c9502f0

File tree

3 files changed

+33
-5
lines changed

3 files changed

+33
-5
lines changed

src/Character.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ public void addWeapon(Weapon newWeapon) {
5151
* Gets the equipped weapon of this Character
5252
*/
5353
public Weapon getEquippedWeapon() {
54+
if (equippedWeapon == -1) {
55+
return null;
56+
}
5457
return weapons.get(equippedWeapon);
5558
}
5659

src/Fists.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Default weapon for when you are unarmed
3+
*/
4+
public class Fists extends Weapon {
5+
public Fists() {
6+
super("fists", "your hands", 3);
7+
}
8+
9+
10+
@Override
11+
public boolean useOn(Character target) {
12+
target.health -= getBaseDamage();
13+
System.out.println("Slapped for " + getBaseDamage() + " damage.");
14+
return true;
15+
}
16+
}

src/Main.java

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
public class Main {
44
public static void main(String[] args) {
5+
Weapon defaultWeapon = new Fists();
56
ArrayList<Character> characters = new ArrayList<>();
67
/*
78
Adding Your Character to the Arena, by Avery
@@ -34,12 +35,20 @@ public static void main(String[] args) {
3435
continue;
3536
}
3637
int targetIndex = curr.pickTarget(characters);
37-
if (targetIndex != i) {
38-
System.out.println(curr.getName() + " attacked " +
39-
characters.get(targetIndex).getName() +
40-
" with their " + curr.getEquippedWeapon().getName());
38+
if (targetIndex == -1) {
39+
System.out.println(curr.getName() + "'s attack failed because" +
40+
" it couldn't find a good target.");
41+
continue;
42+
}
43+
Character target = characters.get(targetIndex);
44+
Weapon weapon = curr.getEquippedWeapon();
45+
if (weapon == null) {
46+
weapon = defaultWeapon;
4147
}
42-
curr.getEquippedWeapon().useOn(characters.get(targetIndex));
48+
System.out.println(curr.getName() + " attacks " +
49+
target.getName() +
50+
" with their " + weapon.getName());
51+
weapon.useOn(target);
4352
}
4453
System.out.println(characters.get(0).getName() + " won!");
4554
}

0 commit comments

Comments
 (0)