1
\$\begingroup\$

I'm writing a game in Java and am struggling to think how to appropriately manage character's bodies. My current structure is, in relevant part:

public class Character{
    private Body body;
    private Race race;
}

public class Body{
   private Leg rightLeg;
   private Leg leftLeg;
   //etc

   //the constructor takes a single Race argument and constructs a default
   //body for a member of that race

   public Leg getRightLeg(){
       return rightLeg;
   }

   ///etc
}

public class BodyPart(){
  //assorted instance variables and appropriate getters and setters
}

public class Leg extends BodyPart(){
  //leg specific stuff
}

public class AdvancedLeg extends Leg{
    //various different ways of improving body parts - magical enhancement 
    //for example.  There are a number of these classes 
    public AdvancedLeg(Leg l){
        //make leg better
    }
}

But this isn't working because each character must have the same basic body structure - 2 arms, 2 legs, one torso, one head, etc. Sure, I could have public class QuadrapodBody or similar (and make Body into an interface) but I certainly don't want to be getting in to public class OneHeadTwoRightArmsOneLeftArmOneRightLegOneLeftLegBody implements Body.

In essence I want to be able to flexibly assign body plans to each character and be able to manage getting body parts without having to write a potentially infinite number of classes each with a subtly different set of instance variables and getters/setters.

Hopefully my question is clear enough.

| improve this question | | | | |
\$\endgroup\$
1
\$\begingroup\$

Instead of a separate variable for each bodypart, as in

private Leg rightLeg;
private Leg leftLeg;

have a list of bodyparts:

private List<BodyPart> bodyParts = new List<>();

You can then use getters which return one bodypart (or all bodyparts) which fulfill a specific criteria. For example:

// returns the first Head of the creature, or null when the creature has no head(s)
public BodyPart getHead() {
      return bodyParts.stream()
                      .findFirst(part -> part instanceof Head)
                      .orElse(null);
}

// returns all legs, arms, tentacles and prehensile tails
public BodyPart[] getExtremities() {
      return bodyParts.stream.filter(part -> part instanceof Extremity).toArray();
}
| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.