0

So I am trying to make a text adventure game for my computer class. I know the basics of C# but obviously I'm missing something because I can't get the code right. I want to make the man ask the player a question that if they answer no it basically repeats the question because they have to answer yes for the game to continue. I tried using a for loop but that didn't work very well. Anyways, this is the code I have:

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?\"");
            }
        }
    }
}

Any help or suggestions for what I could do would be greatly appreciated because I've run out of ideas.

4

4 回答 4

9

您可以使用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循环,这取决于您的要求。

于 2013-05-08T16:40:46.740 回答
3

我认为您最好的选择是使用 do while 循环,请查看MSDN 示例以获取指南

using System;
public class TestDoWhile 
{
    public static void Main () 
    {
        int x = 0;
        do 
        {
            Console.WriteLine(x);
            x++;
        } while (x < 5);
    }
}
于 2013-05-08T16:42:36.167 回答
0

使用while循环并不断重复,直到你得到你想要的答案。

于 2013-05-08T16:40:57.760 回答
0

像这样的东西:

bool isGoodAnswer= false;
while (!isGoodAnswer)
{
// Ask the question
// Get the answer
isGoodAnswer = ValidateAnswer(answer);
}
于 2013-05-08T16:43:11.450 回答