【发布时间】:2015-08-13 18:05:24
【问题描述】:
所以我正在开发一个文本冒险来提高我的编程技能(只是一个初学者),我正在为它开发一个新的战斗系统,因为旧的战斗系统真的很无聊。所以我遇到了一个剪刀石头布系统,但我想要一个像剪刀石头布一样的系统,有 5 个选项供玩家选择,以及攻击玩家的敌人或怪物。
我使用了很多 if 语句,实际上并没有花太长时间,但我想知道是否有更好的方法来执行此操作,以便我的代码更高效,而不是那么大。
public static void ResultsOfMoves(string PlayerMove, string MonsterMove, Monster CurrentMonster, Weapon CurrentWeapon, Armor CurrentArmor, Player CurrentPlayer)
{
//Monster Responses to Player
if (PlayerMove == "dodge" && MonsterMove == "heavy"||MonsterMove == "stealth")
{
if (MonsterMove == "heavy") { MonsterHeavyAttack(); }
if (MonsterMove == "stealth") { MonsterStealthAttack(); }
}
else if (PlayerMove == "charge" && MonsterMove == "dodge"||MonsterMove == "stealth")
{
if (MonsterMove == "dodge") { MonsterDodge(); }
if (MonsterMove == "stealth") { MonsterStealthAttack(); }
}
else if (PlayerMove == "block" && MonsterMove == "charge" || MonsterMove == "dodge")
{
if (MonsterMove == "charge") { MonsterChargeAttack(); }
if (MonsterMove == "dodge") { MonsterDodge(); }
}
else if (PlayerMove == "heavy" && MonsterMove == "block" || MonsterMove == "charge")
{
if (MonsterMove == "block") { MonsterBlock(); }
if (MonsterMove == "charge") { MonsterChargeAttack(); }
}
else if (PlayerMove == "stealth" && MonsterMove == "heavy" || MonsterMove == "block")
{
if (MonsterMove == "heavy") { MonsterHeavyAttack(); }
if (MonsterMove == "block") { MonsterBlock(); }
}
//Players Responses To Monster
if (MonsterMove == "dodge" && PlayerMove == "heavy" || PlayerMove == "stealth")
{
if (PlayerMove == "heavy") { MonsterHeavyAttack(); }
if (PlayerMove == "stealth") { MonsterStealthAttack(); }
}
else if (MonsterMove == "charge" && PlayerMove == "dodge" || PlayerMove == "stealth")
{
if (PlayerMove == "dodge") { MonsterDodge(); }
if (PlayerMove == "stealth") { MonsterStealthAttack(); }
}
else if (MonsterMove == "block" && PlayerMove == "charge" || PlayerMove == "dodge")
{
if (PlayerMove == "charge") { MonsterChargeAttack(); }
if (PlayerMove == "dodge") { MonsterDodge(); }
}
else if (MonsterMove == "heavy" && PlayerMove == "block" || PlayerMove == "charge")
{
if (PlayerMove == "block") { MonsterBlock(); }
if (PlayerMove == "charge") { MonsterChargeAttack(); }
}
else if (MonsterMove == "stealth" && PlayerMove == "heavy" || PlayerMove == "block")
{
if (PlayerMove == "heavy") { MonsterHeavyAttack(); }
if (PlayerMove == "block") { MonsterBlock(); }
}
}
【问题讨论】:
-
有很多方法可以提高效率。例如,如果你使用枚举而不是字符串,你会更加紧凑。您还可以创建函数指针表(C# 中的委托),然后在字典中查找下一个操作并在一行代码中执行它。我会让更熟悉 C# 的人用代码说明这一点。
-
这最好放在程序员交流中。
-
@Makoto:可能是 C++,其
std::string class支持使用==进行比较。 OP,你能添加一个语言标签吗? -
如果代码按预期工作并且您正在寻求改进,欢迎您在 Code Review 上发帖。如果您决定这样做,我会强烈建议更改您的标题以描述代码的作用。
-
@Makoto 在 C# 中的字符串可以用 == 进行比较,不需要 Java 风格的
Equals()
标签: c# processing-efficiency space-efficiency