Gusti
Gusti

Reputation: 71

Method from interface takes one parameter but it will be used with 2 different objects

I have to do a simple rpg game and there are 2 types of entities: heroes and monsters. Attack method will be implemented in both classes and it is contained by a interface called IAttack. The problem is that this method take a Monster type as parameter for hero class and a Hero type as parameter for monster class.

The code looks something like this:

The interface:

interface IAttack
{
     void Attack(Object oponnnent);
}

The Hero class(which implements IAttack):

public void Attack(Monster opponent)
{
    //code goes here
}

The Monster class(which implements IAttack):

public void Attack(Hero opponent)
{
    //code goes here
}

The problem is I can not pass different types of arguments.

Upvotes: 1

Views: 132

Answers (2)

TVOHM
TVOHM

Reputation: 2742

Why not have two interfaces? Something that can attack and something that can be attacked?

public interface IAttackable
{
    void OnAttacked(IAttacker attacker);
}

public interface IAttacker
{
    void OnAttack(IAttackable opponet);
}

public class Hero : IAttacker, IAttackable
{
    public void OnAttack(IAttackable opponet)
    {
    }

    public void OnAttacked(IAttacker attacker)
    {
    }
}

public class Monster : IAttacker, IAttackable
{
    public void OnAttack(IAttackable opponet)
    {
    }

    public void OnAttacked(IAttacker attacker)
    {
    }
}

Upvotes: 0

Darren
Darren

Reputation: 70728

You could make an abstract class that Monster and Hero dervice from.

public abstract class PlayerType
{
    public abstract int Health();
}

Then in your interface use the new abstract type:

interface IAttack
{
   void Attack(PlayerType oponnnent);
}

Monster class:

public class Monster : PlayerType, IAttack
{
    public override int Health()
    {
        return 100;
    }

    public void Attack(PlayerType hero)
    {

    }
}

Hero class:

public class Hero : PlayerType, IAttack
{
    public override int Health()
    {
       return 500; // He is a hero afterall ;)
    }

    public void Attack(PlayerType monster)
    {

    }
}

Upvotes: 2

Related Questions