Using inheritance and polymorphism to solve a common game problem
- by Barry Brown
I have two classes; let's call them Ogre and Wizard. (All fields are public to make the example easier to type in.)
public class Ogre
{
int weight;
int height;
int axeLength;
}
public class Wizard
{
int age;
int IQ;
int height;
}
In each class I can create a method called, say, battle() that will determine who will win if an Ogre meets and Ogre or a Wizard meets a Wizard. Here's an example. If an Ogre meets an Ogre, the heavier one wins. But if the weight is the same, the one with the longer axe wins.
public Ogre battle(Ogre o)
{
if (this.height > o.height) return this;
else if (this.height < o.height) return o;
else if (this.axeLength > o.axeLength) return this;
else if (this.axeLength < o.axeLength) return o;
else return this; // default case
}
We can make a similar method for Wizards.
But what if a Wizard meets an Ogre? We could of course make a method for that, comparing, say, just the heights.
public Wizard battle(Ogre o)
{
if (this.height > o.height) return this;
else if (this.height < o.height) return o;
else return this;
}
And we'd make a similar one for Ogres that meet Wizard. But things get out of hand if we have to add more character types to the program.
This is where I get stuck. One obvious solution is to create a Character class with the common traits. Ogre and Wizard inherit from the Character and extend it to include the other traits that define each one.
public class Character
{
int height;
public Character battle(Character c)
{
if (this.height > c.height) return this;
else if (this.height < c.height) return c;
else return this;
}
}
Is there a better way to organize the classes? I've looked at the strategy pattern and the mediator pattern, but I'm not sure how either of them (if any) could help here. My goal is to reach some kind of common battle method, so that if an Ogre meets an Ogre it uses the Ogre-vs-Ogre battle, but if an Ogre meets a Wizard, it uses a more generic one. Further, what if the characters that meet share no common traits? How can we decide who wins a battle?