C# 代码的While循环和If语句
我正在编写一个程序,在这个程序中,你会遇到一个怪物,然后给你选择是攻击还是防御。当攻击代码时看起来不错,但当我进入防御程序时,程序就会关闭。当玩家HP或怪物HP为0时 { 控制台。WriteLine(“你攻击了野兽!”); 控制台.WriteLine(“你造成了”+玩家攻击+“伤害”); 随机数-=playerAttack; Console.WriteLine(“它的HP是:“+randomNumber”); Console.WriteLine(); { Console.ReadLine(); 控制台.WriteLine(“它反击了!它发了”+playerAttack); playerHealth-=PlayerTack; Console.WriteLine(“您有”+玩家健康+“剩余生命”); Console.WriteLine(); userInput=playerChoice(); } } 如果(随机数0) { 控制台。WriteLine(“你准备好防守了!”); 控制台。WriteLine(“怪物攻击了!”); 玩家健康-=1; WriteLine(“你阻止了它被攻击,只损失了1点生命”); WriteLine(“您现在拥有:“+playerHealth+”HP”); Console.WriteLine(); userInput=playerChoice(); Console.ReadLine(); } } } 您需要某种“外环”。你的程序结构就像C# 代码的While循环和If语句,c#,loops,while-loop,C#,Loops,While Loop,我正在编写一个程序,在这个程序中,你会遇到一个怪物,然后给你选择是攻击还是防御。当攻击代码时看起来不错,但当我进入防御程序时,程序就会关闭。当玩家HP或怪物HP为0时 { 控制台。WriteLine(“你攻击了野兽!”); 控制台.WriteLine(“你造成了”+玩家攻击+“伤害”); 随机数-=playerAttack; Console.WriteLine(“它的HP是:“+randomNumber”); Console.WriteLine(); { Console.ReadLine();
userInput = playerChoice();
if (userInput == "Attack") {
while (userInput == "Attack") {
....
userInput = playerChoice();
}
} else if (userInput == "Defend") {
while (userInput == "Defend") {
....
userInput = playerChoice();
}
}
当您第一次输入“攻击”时,程序进入第一个if
分支,并停留在那里,直到您停止命令更多的攻击。然后它离开if
构造并终止
我想你想要像这样的东西
userInput = playerChoice();
while (userInput == "Attack" || userInput == "Defend") {
if (userInput == "Attack") {
while (userInput == "Attack") {
....
userInput = playerChoice();
}
} else if (userInput == "Defend") {
while (userInput == "Defend") {
....
userInput = playerChoice();
}
}
}
因此,在第一次“攻击”之后,您可以按任意顺序输入更多的“攻击”或“防御”。这里有几个问题 去掉这里的大括号:
Console.WriteLine();
{
Console.ReadLine();
Console.WriteLine("It fought back! It dealt " + playerAttack);
playerHealth -= playerAttack;
Console.WriteLine("You have " + playerHealth + " HP left");
Console.WriteLine();
userInput = playerChoice();
}
我假设你有那些空的Console.WriteLine()代码>调用,以便在输出中有一个空行。相反,我建议重构您以前的行,以包含一个额外的换行符,例如:
Console.Write("You have " + playerHealth + " HP left\n\n");
如果您不想重新构建程序流程,要解决玩家或怪物没有剩余HP后出现提示的问题,请在后续调用playerChoice()
时添加此If语句:
我还建议将randomNumber
重命名为更有意义的名称,比如enemyHP
关于“防御”问题,您是否调试了代码以查看该代码分支是否受到攻击?您试图解决的问题是什么?如果你没有明确指出它,你很可能会得到无用的和无关的答案,建议改变风格(如下所示)。不知道为什么而中的循环如果是有意义的。
Console.Write("You have " + playerHealth + " HP left\n\n");
if (playerHealth > 0 && randomNumber > 0)
{
userInput = playerChoice();
}