I’m making a very simple 2D RPG in Java. My goal is to do this in as simple code as possible. Stripped down to basics, my class structure at the moment is like this:
- Physical objects have an x and y
dimension.- Roaming objects are physical objects
that can move().- Humanoid objects are roaming objects
that have inventories of GameItems.- The Player is a singleton humanoid
object that can hire up to 4 NPC Humanoids
to join his or her party, and do other actions, such as fight non-humanoid objects. - NPC Humanoids can be hired by the
Player object to join his or her
party, and once hired can fight for the Player.
- The Player is a singleton humanoid
- Humanoid objects are roaming objects
- Roaming objects are physical objects
So far I have given the Player class a “party” ArrayList of NPC Humanoids, and the NPC Humanoids class a “hired” Boolean.
However, my fight method is clunky, using an if to check the party size before implementing combat, e.g.
public class Player extends Humanoids {
private ArrayList<Humanoids> party;
// GETTERS AND SETTERS for party here
//...
public void fightEnemy(Enemy eneObj) {
if (this.getParty().size() == 0)
// Do combat without party issues
else if (this.getParty().size() == 1)
// Do combat with party of 1
else if (this.getParty().size() == 2)
// Do combat with party of 2
// etc.
My question is, thinking in object oriented design, am I on the right track to do this in as simple code as possible? Is there a better way?
Well, forgetting the overall design, from a basic programming point of view, instead of having that
ifstructure, you should have a method that takes the party size as an argument. That way, you can just pass inthis.getParty().size()and get rid of theifs.i.e.
Where
combatManageris an object (or class, if you want a static version) that knows how to make thingsfight.As I said though, this is not a solution for your design, simply a nicer way to avoid the
ifs.The
Playerclass should not be responsible for making things fight, so perhaps you could change yourfightEnemymethod toengageEnemyor something, and simply have it go to the combatManager with the correct parameters.