4
\$\begingroup\$

I am making a game using Java, LibGDX and Box2D. What would be the best way to create a player that can hold:

  • no item
  • one item from group A
  • one item from group B
  • one item from both groups

example of players, A items & B items

Items from group A can only be used to attack, and are held in the right hand.
Items from group B can only be used to defend, and are held in the left hand.

Should I add the item to the player class and render/update the item in the player class? Or is there any best way to this that I am not aware?

This is the best way I know how to do it:

UML diagram

I would also be interested in any design pattern that could be applied to this situation.

\$\endgroup\$
2
  • \$\begingroup\$ Are there any programmatic differences between A & B type items? Can the player attack with a shield or defend with a gun? \$\endgroup\$
    – Pikalek
    Dec 26, 2016 at 3:06
  • \$\begingroup\$ @Pikalek Yes there are. Itens from type A can only be used to attack and they are positioned on the right hand of the player. Itens from type B can only be used to defend and they are positioned on the left hand of the player. \$\endgroup\$ Dec 26, 2016 at 3:48

1 Answer 1

3
\$\begingroup\$

I'd say, don't sweat it. Your character's two hands are independent of one another, the two items groups have distinct interfaces and are meant to be used in different ways. Just use a properly-typed reference for each hand, there's no need for type erasure or fancy design patterns.

public class Player {

    private DefenceItem leftHandItem;
    private AttackItem  rightHandItem;

    // ...

    public void update() {
        // Update yourself

        if(leftHandItem != null)
            leftHandItem.update();

        if(rightHandItem!= null)
            rightHandItem.update();
    }

    public void draw() {
        // Draw yourself

        if(leftHandItem != null)
            leftHandItem.draw();

        if(rightHandItem!= null)
            rightHandItem.draw();
    }

    public void attack() {
        if(rightHandItem!= null)
            rightHandItem.attack();
    }

    public void defend() {
        if(leftHandItem != null)
            leftHandItem.defend();
    }
}

I've kept these simple void() methods for the example, but passing the required information around won't be problematic since all type information is preserved.

\$\endgroup\$
1
  • \$\begingroup\$ You should only call the methods if there is an item in that hand \$\endgroup\$
    – Bálint
    Dec 26, 2016 at 16:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .