Reputation: 3162
I have a class called "Entity," with two child classes: "Creature" and "Item." (I'm making a game.) Creature has two functions called "Attack," one for attacking Creatures, and one for attacking Items. So far, everything works well.
Now I'm working on the shooting bit, so I have a function called SelectTarget(). It takes all of the Entities (both Creatures and Items) in the player's view that the player can shoot and lets the player choose one.
So here lies the problem: SelectTarget() returns an Entity, but I need some code to figure out whether that Entity is a Creature or an Item, and process it appropriately.
Since this question looks kind of empty without any code, and I'm not 100% sure my explanation is good enough, here's where I'm at:
if (Input.Check(Key.Fire)) {
Entity target = Game.State.SelectTarget.Run();
this.Draw();
if (target != null) {
//Player.Attack(target);
// This won't work, because I have:
// Player.Attack((Creature)Target)
// Player.Attack((Item)Target)
// but nothing for Entity, the parent class to Creature and Item.
return true;
}
}
(If the way the game is laid out seems weird, it's a roguelike.)
Upvotes: 1
Views: 173
Reputation: 14934
What about introducting an interface IAttackable
that both Creature
and Item
implement. Player.Attack
would have the new signature Player.Attack(IAttackable target)
. Every object implementing IAttackable
could get methods for substracting health, or retrieving defense values (for calculation of healthpoints to be reducted), and so on...
Upvotes: 9
Reputation: 21860
try something like:
if(target is Creature)
player.Attack(target as Creature);
else if(target is Item)
player.Attack(target as Item);
Upvotes: 3