instanceof or seperate lists?

so i am making a game, and i use Interface Sprite for my basic class for the game entities

the Sprite only has one method, draw.

then i have the Interface Moveable, Objects that can be moved (and also drawn) implement both (or maybe Moveable should extend the Sprite interface ??)

i have a list to hold the Sprites, so when i iterate through the list should i use instanceof to make sure that i move only moveable objects, or should i have two seperate lists, and call the move method only on the Moveable objects???

edited: there is the solution of having an enum, and inside each implementation the object knows its type, and can be asked for it
but it looks kinda ugly, and so does the instanceof operator (to me)

You could have the move and draw methods in the base object and have the derived objects make the distinction between who is movable and who is not by whether or not the move method actually does anything.
Then you have one list and you call move and draw on all objects and the objects control what is actually done.

your suggestion also occured to me among dozens of others

i am not just trying to make something work, i just want to understand why an approach is better than another

thank you for your answer and time

In games, at least, pretty much everything can be both moved and drawn, and as such you’ll typically have a big superclass for anything that can exist in the world, often called Entity. It contains move(), draw(), and other like-methods, and also has fields for X/Y position, size, etc. This is often a better choice as you also get the fields that can be declared protected and therefore used by subclasses.

Game objects or sprites may not only want to move, but update their transparency, remove themselves after a certain amount of time or some other action. That’s why I’d recommend giving all sprites both an update and draw method, which allows you to put them all into their own list. I take this further with a list of lists to allow me to select which layer the objects will appear on.

Movable objects will move when update is called. Objects that are just there to look pretty (like text) will do nothing when update is called. Other objects will run their own custom code in update.

ok, big picture, forget about the move and draw

we have a game with lots of entities, too complex for Class hierarchy

Advanced Java Game Programming book example: Zombie extends Undead extends Humanoid extends Thing, or Zombie extends Humanoid extends Undead extends Thing
so either all your Undead are also Humanoids (VampireBats??? ) or all of your Humanoids are Undead…

a solution to this approach is having interfaces

so far so good???

(and also, there is the possibility that someone prefers Interface programming from Class)

so for someone who wants to use Interfaces, and every game entity would be implementing the needed interfaces, what is the best solution?? using instanceof to call the holyWaterDamage() on the Zombie, or the getWet() on the main hero ??? or using seperate lists??

of course, when something is as complex, there must be lots and lots of lists… though i assume that if the lists store the references and nothing more, the extra memory needed for objects belonging to more than one, isnt that big

thank you for your answers so far and forgive me for not being specific enough from the very beginning

you should have a look to Component Oriented Programming and Entity Systems , there is a nice discussion about this somewhere on JGO

See this blog post and the discussion bellow.

http://tech.puredanger.com/2007/07/16/visitor/

Disavantages are more upfront work.

is that a book???

thank you for the link (still reading)

nop, this is a different approach than OO to build application

http://www.java-gaming.org/index.php/topic,20589.0.html

A few weeks back I was thinking of building a component oriented system. Reading that discussion on JGO put me off the idea.

So the main issue is ‘how do I find objects of a specific type?’ I personally use both systems but with a bit of reflection. I compare the type directly with class.isInstance rather then instance of, this is for when I’m searching for objects inside the world. I also dynamically sort objects into separate lists inside the collision detection handler. By doing it dynamically it still looks like I’m putting them all into one big collection. Both of these contain all game objects (although there is no reason why you couldn’t push them together and it’d probably be more efficient, but it’s fast enough). The first is for finding objects in a generic fashion, like removing all enemies in the game. The later is used for finding intersections between actors of a specific type.

The code for using them looks a bit like:


Foo foo = getObject( Foo.class );
List<Foo> foos = getObjects( Foo.class );
List<Bar> bars = getIntersectingObjects( Bar.class );

So to solve your Hero/Zombie issue it would be a bit like:


class HolyWater implements Sprite
{
    public void update()
    {
        Hero hero = getIntersectingObject( Hero.class );
        if (hero != null) {
            hero.getWet();
        } else {
            for (Zombie zombie : getIntersectingObjects( Zombie.class )) {
                zombie.holyWaterDamage();
            }
        }
    }
}

But you could also add a HolyWaterReceiver interface that both Hero and Zombie implement. i.e:


class HolyWaterReceiver implements Sprite
{
    public abstract void receive(HolyWater water);
}

class Hero implements HolyWaterReceiver
{
    public void receive(HolyWater water)
    {
        getWet();
    }
}

class Zombie implements HolyWaterReceiver
{
    public void receive(HolyWater water)
    {
        holyWaterDamage();
    }
}

class HolyWater implements Sprite
{
    public void update()
    {
        for (HolyWaterReveiver receiver : getIntersectingObjects( HolyWaterReceiver.class )) {
            receiver.receive( this );
        }
    }
}

This pushes the responsibility of ‘what happens if your hit by holy water’ out to the object being hit.

great stuff to read,

so the answer to my original question is probably “none”

thank you all for your answers

I think really you’re putting too much of your object definition in the hands of your class hierarchy. Instead of all this Poodle extends Dog extends Canine extends Animal extends Entity type ideas you have, you can probably snip off almost all the extra things, like Poodle and Dog for certain, and probably Canine, too.

The functionality that each subclass defines should be pretty major. In my example case, a Poodle is only different from a Dog in how it looks, and maybe how strong it is. That can be translated to fields that are defined differently when you create the object. Just change Poodle’s Sprite to reflect his different look and change his size to reflect his new strength. The differences between Dog and Canine will be similarly small - perhaps a Wolf also extends canine, and the difference between a Wolf and a Dog is that Wolves are bigger and meaner. Again, that comes down to a different Sprite, then perhaps the meanness can go into an “aggression” variable.

Then the specific behavior that a Canine exhibits can also be assigned to a bunch of enumerated separate actions, like walkType = TYPE_FOUR_LEGGED, attackType = TYPE_BITE, etc.

Typically the differences in each subclass are very major, like Entity and HostileEntity and FriendlyEntity. In an RPG, the difference between the two is very large (hostile entities need to have stats for combat, what “friends” they can bring with them, what XP they can give you, etc., whereas friendly entities need to know conversations, quests, item rewards, etc.). You should only have subclasses for information that cannot be logically represented by the superclass.

In your Zombie extends Undead extends Humanoid extends Thing example, Zombie is not at all different from Undead, Undead is barely different from Humanoid, and Humanoid probably isn’t much different from “Thing.” Instead these differences should be defined by different fields, and perhaps you can write a bunch of different behavior scripts they can utilize if you really need to. But typically you’ll stick with even just booleans… isUndead, isHumanoid, etc.

Real-world example:
In the game I’m working on right now, we’ve got:
Entity (comes with position, size, the capability of acting, drawing, doing hit tests, etc.)
Entity > MobileEntity (comes with variables for moving around, like pathfinding, velocity, etc.)
Entity > BackgroundEntity (adds nothing new to the table, but isn’t abstract, overrides act to do nothing except animate)
Entity > MobileEntity > Car (has a bunch of logic for dropping off Customers, lining up in the parking lot, etc.)
Entity > MobileEntity > Customer (has a bunch of logic for paying the Player, waiting in a venue to be ready to get their Car, etc.)
Entity > MobileEntity > Particle (has a bunch of logic for falloff, color changing, animation, flipping around, etc.)
Entity > ParticleEmitter (has a bunch of logic for timing of emitting particles)
Entity > MobileEntity > Valet (has a bunch of logic for driving cars, running back to their zone, etc.)

And those are all the entities that exist in the entire game, which is many thousands of lines long. And if I were redesigning it now I would do away with MobileEntity and BackgroundEntity, just because they have become redundant through so many code refactorings.

Yes don’t go overboard with inheritance. Actually i’m not sure how well the visitor technique described in the link i posted works for games. They are actually real time applications, and the guy making the example works in another area.

I’d actually read the Game object component system thread too. Might be worth a try.

so, i should leave the theoritical search of a “best design” and just be practical
a game should be playable (thus completed and tested) after all
thank you all for your great advice

I think works very well and fully agree with this idea; but only if you are never going to be searching for Dog, Poodle or Wolf! Then it doesn’t matter if they are stored as a Canine and you can build Factory classes to automate building these (and more) types of Canines.

But I do not recommend this part of the design. Your adding methods in order to state the type of the object, which you can already do quite happily with inheritance. If the object is Undead then it should be an instance of Undead (or of a sub-class).

Overall using a common class for objects (i.e. Canine for Dog, Wolf and Poodle) only works well if their differences are very minor (like different image, attack value, hp, etc). Once you start adding differences in behaviour and type you’ll begin adding lots of boiler plate code just to get the same effect as using inheritance.

I tend to agree with Demonpants on this one (surprise!). The aim is to reduce the depth of your inheritance tree. My personal preference is to have it reduced to 0. Inheritance is best avoided - it restricts you into working with some kind of hierarchy, where a hierarchy is often totally not suited to handle your game logic. You end up with moving more and more functionality up the tree, until (in worst case) you end up with a huge ‘magic blob’ having functionality that you can turn on and off.

Composition over inheritance is here to save the day. You can use it as ‘mixins’ from other language, so that you can simply add or remove functionality (even at runtime) from an entity. The more complex the game is, the greater the advantages become from using composition. In a tiny game, it’s just a royal pain in the behind.

`Entity dog = new Entity();
dog.setSprite(myDogSprite);
Movement2D mov = new Movement2D();
BiteWeapon = new BiteWeapon();
dog.addComponent(mov);
dog.addComponent(new DogAI());
dog.addComponent(weapon);

mov.enqueueMoveTo(x1, y1);
mov.enqueueMoveTo(x2, y2);
weapon.enqueueAttack();

while(true)
dog.tick();`

:wink:

Yeah, seems like Riven is getting back towards the component method of doing things - in the end it looks like anything works, but you should find what’s best for you. However, using instanceof all over the place is a bit slow, so you should be careful with having a bagillion classes. Otherwise there’s not much difference, in the end, between all inheritance, all components, or some shade in between.

One big reason not to use inheritance, however, is for updating purposes. Because Java is JIT you can always just have people download new .class files (like if you added in Vampire after releasing the game) instead of a whole new download, but this won’t work if you’re planning on distributing in binary, and either can be annoying and is more prone to classpath problems. If you’ve got a component system then all you need to do is include another constructor with some different parameters to it, which is easier to add on to an existing project.

What really will aid you the best in the end, though, is if you can successfully write down at least most of the stuff you will need for your game. Do some UML-type stuff: this monster does this and this item does that, and these two can share that functionality, etc. Once you’ve got a steady roadmap to go off of, you’ll be in a much better place to decide how you want to implement everything.