2013-02-04 27 views
1

當我做了我的遊戲,我偶然發現了一個小問題。我有一個方法攻擊(),當我的角色攻擊敵人時必須執行。例如:我如何設置一個參數來接受稍後要聲明的對象?

public override void Attack(Object theEnemy) 
{   
     theEnemy.Health = theEnemy.Health - this.attack 
} 

例如:我攻擊一個精靈。 Elf對象需要是參數,問題是參數正在尋找Object,而不是Elf。如果我想攻擊其他敵方物體,如獸人,矮人等,我也需要參數才能接受任何物體。可能嗎?

+4

使用由你的所有敵人的生物實現的接口? – ScruffyDuck

回答

7

您可以在此情況下,例如爲:

interface IEnemy 
{ 
    void TakeDamage(int attackPower); 
} 

public Elf: IEnemy 
{ 
    // sample implementation 
    public void TakeDamage(int attackPower) 
    { 
     this.Health -= attackPower - this.Defense; 
    } 
} 

// later on use IEnemy, which is implemented by all enemy creatures 
void Attack(IEnemy theEnemy) 
{   
     theEnemy.TakeDamage(attack) 
} 
1

使用的界面,最好是單獨的關注和使用OOP概念。 使用接口。

interface IGameMethods 
{ 
    void Attack(int yourValueForAttackMethod); 
} 

實施

public Elf: IGameMethods 
{ 
    // implementation of IGameMethods 
} 
3

好像什麼可以「攻擊」必須實現一個接口給訪問所需的性能和/或方法。

因此,舉例來說,你可以做

public interface IAttackable 
{ 
    void ReduceHealth(int amount); 
} 

然後實現它的任何生物是易受攻擊的 - 即精靈

public class Elf : IAttackable 
{ 
    public void ReduceHealth(int amount) 
    { 
     this.Health -= amount; 
    } 
} 

然後用法是

public override void Attack(IAttackable theEnemy) 
{   
     theEnemy.ReduceHealth(this.attack); 
} 
2

你可以創建每個敵方對象實現的接口,或者您可以創建每個enemby對象所基於的基類d。

public interface IEnemyCreature{ 

void ReduceHealth(int Amount) 

} 

public Elf: IEnemyCreature{ 
... 
} 

編輯 - WalkHard已經描述的代碼比我9-)

相關問題