2011-09-02 61 views
0

我正在製作一個控制檯RPG,並且對泛型非常新穎。我的問題是,我想要一個英雄(存儲在英雄列表通用)攻擊怪物(存儲在敵人列表通用)。我擁有的問題是讓英雄從我的怪物中選擇一個目標,然後修改怪物的hpcurrent。對於一個怪物和英雄來說這很容易,但是當我擴展遊戲時,我打算擁有幾種類型的怪物和英雄;因此我想爲我的英雄使用一段代碼,它可以從通用中挑選一件物品並修改它的統計數據。有兩種泛型的原因是因爲它讓我更容易看到所有英雄或怪物是否都死了。C#如何修改列表<class>

我會後對怪物的代碼(這等同於英雄的,這些數字都只是不同):

class Orc : Character 
{ 
    public Orc() 
    { 
     this.hpcurrent = 12; 
     this.hpmax = 12; 
     this.mpcurrent = 0; 
     this.mpmax = 0; 
     this.strength = 6; 
     this.defense = 4; 
     this.magicstrength = 0; 
     this.magicdefense = 2; 
     this.agility = 4; 
     this.level = 3; 
     this.isaliveBool = true; 
     this.name = "Orc"; 
     this.weakness1 = "fire"; 
     this.weakness2 = "thunder"; 
     this.battlemove = null; 
     this.typeofcharacter = "monster"; 
    } 

的怪物列表中的代碼是:

public List<Character> enemies() 
    { 
     List<Character> enemies = new List<Character>(); 
     enemies.Clear(); 
     enemies.Add(new Orc()); 
     return enemies; 
    } 
+1

聲明'enemies.Clear();'是無用的,因爲你剛剛在上一行實例化了列表......你正在清空一個空集合。 –

+0

表示,我不明白正在嘗試做什麼。你在調用「修改」列表是什麼?也許你想繼承'CollectionBase':'公共類CharacterList:CollectionBase {...有些東西不在列表 ...}'? –

回答

0

你可以使用這樣的事情:

public List<Character> Enemies 
{ 
    if (_Enemies == null) 
    { 
     _Enemies = new List<Character>(); 
     _Enemies.Clear(); 
     _Enemies.Add(new Orc()); 
    } 
    return _Enemies; 
} 
private List<Character> _Enemies; 

然後你可以使用像這樣:

obj.Enemies[0].HP += 25; 
0

您需要爲您的Character類添加一個標識符屬性,以識別特定的敵方物體並對其執行一些操作。 Guid類適用於此目的。

0

真的不確定你想要完成什麼,但類是C#中的引用類型。這意味着如果你修改了集合之外的同一個敵人物體,那麼這個改變也反映在集合體內。什麼是不明確的是你打算如何使用這個。什麼對象擁有你的敵人列表?你如何從列表中找回某個敵人?一旦你從列表中擁有了你想要的敵人,更新就變得微不足道了。