嘿,伙计们.我希望有人能够帮我弄清楚如何增加枚举.我有一个使用枚举来获得杀死敌人的点数的游戏,我希望每当敌人被杀时敌人的值增加10.这是我对枚举的代码:
public enum gamescore// Enumeration to hold the score values of the enemies
{
Martian = 10,
Vesuvian = 20,
Mercurian = 30,
Meteor = 50,
MotherShip = 100,
Destroyer = 200
}
Run Code Online (Sandbox Code Playgroud)
以及在敌人死亡时从另一个班级调用得分的方法:
public int GetScore()// The method that utilieses the enumeration to get the score for the enemy killed
{
if (this is Martian)
{
return (int)gamescore.Martian;
}
else if (this is Vesuvian)
{
return (int)gamescore.Vesuvian;
}
else if (this is Mercurian)
{
return (int)gamescore.Mercurian;
}
else if (this is Destroyer)
{
return (int)gamescore.Destroyer;
}
else if (this is Meteor)
{
return (int)gamescore.Meteor;
}
else if (this is Mothership)
{
return (int)gamescore.MotherShip;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?我只能提出复杂的方法来做到这一点,我认为甚至不行.
另外我想知道,我有一个高分标签,如果它低于分数就会更新,所以高分会成为分数,但是当应用程序重新启动时,如果游戏完成或者玩家用尽了生命,那么高分会重置为零,有没有办法保持高分值,所以最高分始终存在?
我非常感谢你对我的问题的帮助,我真的很喜欢.
谢谢!
在这种情况下,我不会将它存储为枚举 - 它听起来更像是范围标记而不是谨慎的值.我可能有一些常量和检查方法
if(score>100) return "awesome";
if(score>40) return "meh";
Run Code Online (Sandbox Code Playgroud)
等等
但是要回答有关增加枚举的问题:您可以将其强制转换为基类型(通常int):
myEnumValue = (MyEnum)((int)myEnumValue + 10);
Run Code Online (Sandbox Code Playgroud)
这种设计不是非常面向对象的.更好的方法是拥有一个IEnemy界面.该接口需要一种GetScore方法(可能是其他方法).那个方法可以返回敌人的价值.然后你为每个实现IEnemy界面的敌人都有一个单独的类.
public interface IEnemy{
int GetScore();
}
public class Martian : IEnemy{
int GetScore(){ return 10; }
}
public class Vesuvian : IEnemy{
int GetScore(){ return 20; }
}
...
Run Code Online (Sandbox Code Playgroud)
与使用枚举相比,这有许多好处,例如,您可以拥有具有相同分数但具有不同其他属性的敌人.