This is a code design question. I am making a tile based game where one class character can traverse over a certain kind of tile while another class cannot. In this situation, there is warrior class that can walk over stone tiles. There is another class, called a “burrower” (digs underground), that cannot traverse over the stone tiles (i.e. cannot burrow into solid rock). My question is, how can I design the classes so that an entity of class type Warrior (inherits from Entity class) can traverse over a stone tile, while an entity of class type Burrower (also inherits from Entity class) cannot traverse over a stone tile?
The Entity class has the pure virtual function canTraverse(Tile). It takes a tile object as a parameter and checks if this entity can traverse it. My first thought went to polymorphism (http://www.cplusplus.com/doc/tutorial/polymorphism/) and how two different classes inheriting from the same super class can behave differently depending on the class type. My issue here, though, is how can I make the class Burrower behave differently from Warrior when the function canTraverse(Tile) not only depends on the subclass (Burrower or Warrior), but also its relationship to the type of tile?
I have an enum: Enum TileType {GRASS, STONE} The Tile class has a member variable tileType which is of type enum TileType. Subclasses of Tile include Stone and Grass, i.e. Stone and Grass classes both inherit from Tile. So, in the canTraverse function for the Burrower class, I would have something like this:
Boolean Warrior::canTraverse(Tile tile)
{
// a warrior can traverse any kind of tile
Return True;
}
Boolean Burrower::canTraverse(Tile tile)
{
If(tile.getType() == STONE)
{
Return False;
}
Return True;
}
This should work, but it looks dangerously close to if I were calling instanceof:
If ( tile instanceof STONE)
Return False;
Which is going against polymorphism (http://www.artima.com/interfacedesign/PreferPoly.html). Is there a better way/better coding practice I can follow to have the Burrower class figure out that it cannot traverse a tile that is of type STONE?