Skip to content
This repository was archived by the owner on Dec 20, 2025. It is now read-only.

Commit 4ab6133

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 07bd15e commit 4ab6133

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
@@ -4,6 +4,7 @@
44

55
public class Main {
66
public static void main(String[] args) {
7+
Weapon defaultWeapon = new Fists();
78
ArrayList<Character> characters = new ArrayList<>();
89
/*
910
Adding Your Character to the Arena, by Avery
@@ -37,12 +38,20 @@ public static void main(String[] args) {
3738
continue;
3839
}
3940
int targetIndex = curr.pickTarget(characters);
40-
if (targetIndex != i) {
41-
System.out.println(curr.getName() + " attacked " +
42-
characters.get(targetIndex).getName() +
43-
" with their " + curr.getEquippedWeapon().getName());
41+
if (targetIndex == -1) {
42+
System.out.println(curr.getName() + "'s attack failed because" +
43+
" it couldn't find a good target.");
44+
continue;
45+
}
46+
Character target = characters.get(targetIndex);
47+
Weapon weapon = curr.getEquippedWeapon();
48+
if (weapon == null) {
49+
weapon = defaultWeapon;
4450
}
45-
curr.getEquippedWeapon().useOn(characters.get(targetIndex));
51+
System.out.println(curr.getName() + " attacks " +
52+
target.getName() +
53+
" with their " + weapon.getName());
54+
weapon.useOn(target);
4655
}
4756
System.out.println(characters.get(0).getName() + " won!");
4857
}

0 commit comments

Comments
 (0)