Rhys Davis
Rhys Davis

Reputation: 996

Java Game Object Design

So I'm having trouble with a simple RTS design.

Basically I want to have a Model and a Controller, where people can program their own AI's to play the game, so I need some form of Interface that sits between the Model and the Controller that allows the Players to control their units without being able to 'set' things in the unit like a units stats.

So I figured to reduce code re-use I'd use a hierarchical structure for creating a unit that does different things in OO:

Player Owned Object -> Object with Stats (health, attack) -> Object that can Attack -> Object that can move -> Unit

So a unit is an object that: is player owned, has stats, can attack, and can move

My problem is this: How do I create some form of interface that works with all this inheritence? So that the interface returns stats if the object inherits 'Object with Stats' as well as the other 'attributes' of the unit. Is it possible with this kind of inheritence? or should I be doing this a different way?

I hope that makes sense! Thanks

Upvotes: 2

Views: 1312

Answers (2)

djna
djna

Reputation: 55957

I don't think a hierarchy is what you need.

The way you have this set up Objects With Stats inherit from Objects that can Attack. This implies that every object that has stats can attack - is that what you mean to say? What about a purely defensive object?

I think instead you have a number of capability Interfaces and certain objects implement certain of those so:

 Monster implements Attacker, Mover, StatProvider, HurtReceiver

 TreasureChest implements Attacker, StatProvider, Movable, HurtReceiver

 Map implements Movable

Upvotes: 4

Andreas Dolk
Andreas Dolk

Reputation: 114847

From your question I assume you have something like this:

public interface Unit extends Owned, StatsProvider, Attacking, Moveable {
  // ...
}

and a concrete implementation like

public class Knight implements Unit {
  // ...
}

Now, for example, if we want to move all moveable objects of a player, we could say

List<Owned> playerOwnedObjects = getObjectsFor("Carl");  // you know what I mean...
for (Owned playerOwnedObject:playerOwnedObjects) {
  if (playerOwnedObject instanceof Moveable) {
    ((Moveable) playerOwnedObject).moveTo(getTargetLocation());
  }
}

Hope I haven't misunderstood your question...

Upvotes: 0

Related Questions