我正在创建一个C#控制台应用程序游戏,该游戏除其他事项外还管理角色及其库存。我有各种各样的物品,玩家可以在库存中存放。特别是一件物品给我麻烦,药水物品。这是玩家使用的物品,并且会增加他的一项属性(即生命值或魔力点)。但是上升的状态由Potion类的字符串属性指示。
这是我的代码:
代表游戏角色的Player类
protected $middleware = [
...
\App\Http\Middleware\Cors::class
]
Potion类继承自的Item类:
public class Player
{
//Stats of the player
public int HP;
public int MP;
public int Strength;
public int Defence;
public void UseItem(Item item) //The parameter is the Item to be used. A potion in my case
{
//The potion must rise the stat indicated in its attribute "Bonus Type"
}
}
最后是Potion类:
public class Item
{
public string Name; //Name of the item
public int Bonus; //The stat bonus that the item give to the Player
}
这是我的问题: 我在Player类的UseItem()方法中写了什么,以获取所用药水的属性“ BonusType”,并据此提高正确的属性?
答案 0 :(得分:1)
您需要找出在C#6中使用哪种物品:
public void UseItem(Item item)
{
switch(item)
{
case Potion potion:
if(potion.BonusType == "Whatever")
{
//do your stuff
}
break;
}
}
但是,正如@Neijwiert提到的那样……这并不是一个很好的设计,因为这样一来,您就要对播放器承担全部责任……更好的是:
public class Player
{
//Stats of the player
public int HP { get; set; }
public int MP { get; set; }
public int Strength { get; set; }
public int Defence { get; set; }
public void UseItem(Item item) //The parameter is the Item to be used. A potion in my case
{
item.Use(this);
}
}
public abstract class Item
{
public string Name { get; set;} //Name of the item
public abstract void Use(Player player);
}
public enum BonusType
{
HP,
MP,
Strength,
Defence
}
public class Potion : Item
{
public BonusType BonusType { get; set; }
public int Amount { get; set; }
public override void Use(Player player)
{
switch (BonusType)
{
case BonusType.HP:
player.HP += Amount;
break;
case BonusType.MP:
player.MP += Amount;
break;
case BonusType.Strength:
player.Strength += Amount;
break;
case BonusType.Defence:
player.Defence += Amount;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
现在您可以拥有一整套操纵玩家并执行各种效果的道具,并且效果由道具而非玩家来管理。
答案 1 :(得分:0)
为什么不从简单的转换开始?
if (item is Potion)
{
var potion = (Potion) item;
Console.WriteLine(potion.BonusType);
}
在最新版本的c#中,您可以将支票与强制类型转换合并
if (item is Potion potion)
{
Console.WriteLine(potion.BonusType);
}
或者,切换类型为check的语句
switch (item)
{
case Potion potion:
Console.WriteLine(potion.BonusType);
break;
}
答案 2 :(得分:0)
简单方法:
public void UseItem(Item item)
{
switch(item.BonusType)
case "Health Bonus": // one of the "string BonusType"
player.HP = player.HP + Bonus;
break;
case "Magical Bonus": // one of the "string BonusType"
player.HP = player.MP+ Bonus;
break;
default:
// in case of no matchings.
break;
}
}
我想尝试你的游戏!