我如何让相同的代码重复,直到玩家的答案不同

本文关键字:答案 玩家 代码 | 更新日期: 2023-09-27 18:12:35

所以我正在尝试为我的计算机课制作一款文本冒险游戏。我知道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?'"");
            }
        }
    }
}

我已经无计可施了。

我如何让相同的代码重复,直到玩家的答案不同

您可以使用while loop:

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循环,这取决于您的需求。

我认为你最好的选择是使用do while循环,查看MSDN示例的指南

using System;
public class TestDoWhile 
{
    public static void Main () 
    {
        int x = 0;
        do 
        {
            Console.WriteLine(x);
            x++;
        } while (x < 5);
    }
}

使用while循环,直到你得到你想要的答案。

像这样:

bool isGoodAnswer= false;
while (!isGoodAnswer)
{
// Ask the question
// Get the answer
isGoodAnswer = ValidateAnswer(answer);
}