所以我正在尝试为我的计算机课程制作一个文本冒险游戏。我知道C#的基础知识,但显然我错过了一些东西,因为我无法正确使用代码。我想让这个男人问玩家一个问题,如果他们回答否,它基本上会重复这个问题,因为他们必须回答是,游戏才能继续。我尝试使用for循环但是效果不好。无论如何,这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("MINECRAFT TEXT ADVENTURE: PART 1!");
Console.WriteLine("\"Hello traveller!\" says a man. \"What's your name?\"");
string playerName = Console.ReadLine();
Console.WriteLine("\"Hi " + playerName + ", welcome to Minecraftia!\nI would give you a tour of our little town but there really isn't much left to\nsee since the attack.\"");
Console.WriteLine("He looks at the stone sword in your hand. \"Could you defeat the zombies in the hills and bring peace to our land?\"");
string answer1 = Console.ReadLine();
if (answer1 == "yes")
{
Console.WriteLine("\"Oh, many thanks to you " + playerName + "!\"");
answerNumber = 2;
}
else if (answer1 == "no")
{
Console.WriteLine("\"Please " + playerName + "! We need your help!\"\n\"Will you help us?\"");
answerNumber = 1;
}
else
{
Console.WriteLine("Pardon me?");
answerNumber = 0;
}
for (int answerNumber = 0; answerNumber < 2;)
{
Console.WriteLine("\"We need your help!\"\n\"Will you help us?\"");
}
}
}
}
对于我能做的任何帮助或建议都会非常感激,因为我的想法已经用完了。
答案 0 :(得分:8)
您可以使用while
循环:
while (answer != "yes")
{
// while answer isn't "yes" then repeat question
}
如果您想进行不区分大小写检查,请:
while (!answer.Equals("yes", StringComparison.InvariantCultureIgnoreCase))
{
// while answer isn't "yes" then repeat question
}
您也可以尝试使用do-while
循环,具体取决于您的要求。
答案 1 :(得分:1)
我认为你最好的选择是使用do while循环,查看MSDN example获取指南
using System;
public class TestDoWhile
{
public static void Main ()
{
int x = 0;
do
{
Console.WriteLine(x);
x++;
} while (x < 5);
}
}
答案 2 :(得分:0)
使用while循环并继续重复,直到得到你想要的答案。
答案 3 :(得分:0)
这样的事情:
bool isGoodAnswer= false;
while (!isGoodAnswer)
{
// Ask the question
// Get the answer
isGoodAnswer = ValidateAnswer(answer);
}