Friday, 18 December 2015

Refined game object class hierarchy

This is again a bit technical blog entry, but nothing new here. For long I have been cautious to not use inheritance as much as it would have been possible. A complex class hierarchy certainly has its own features to watch out, but now when the level map has become more of a owner of instances it was time to try something new.

The main problem with too simple hierarchy is that the base class may contain data not needed for all game object types. It's an easy way to handle objects, but with cost of having "empty" data for in fact most game object types.

I have learned to avoid big refactorings so I started to move routines from the base class to a new class one by one and then compiling to see what happens. The new class is called U_Mover and as name implicates it handles moving. It's sitting in between the base class and three derived object types: item, movable (objects that can be pushed) and monster(+player). Only these object types move so it's obvious that you don't need specific location data and move commands for other object types.

The surprising thing about this was how base class continues working as if nothing had happened. It's of course quite easy to explain by rigid use of the public interface. The biggest change was in a template routine that used to fetch the object from a list with Is_Here() function. Since it was moved to U_Mover it stopped working for all other object types. But it was about to change anyway, because the tile class will own objects that don't move. Even moving objects have a pointer in the tile class for finding them quickly without having to browse through a list of objects. It's still uncertain which object types should be stored in a list and which ones could be owned by the tile class, but it will be decided later.

Sometimes a list is better or even required, but it doesn't have to own the objects. It can be a quick way to scan through objects without having to visit each map tile of the level.

No comments:

Post a comment