0

我正在 C# 上的 Visual Studio 上制作游戏(在控制台中)。这是关于对话的,你可以用2个选项来回答它们,一个键(用于回答第一个问题)是1,另一个是2。问题是当你按一个键时,你不能按另一个键更多,我的意思是,如果你按1,你就不能按2,反之亦然。

static void Main(string[] args)
{
    Console.WriteLine("Press 1 or 2 please...");
    //I know there are some errors in this code, i'm new at c#
    ConsoleKeyInfo number1;
    do
    {
        number1 = Console.ReadKey();
        Console.WriteLine("Number 1 was pressed");
        //This is the 1st answer
    }
    while (number1.Key != ConsoleKey.D1);
    ConsoleKeyInfo number2;
    //The problem is that when I already pressed D1 (1), I shouldn't be
    //able to press D2 (2). And if I press D2 (2), I shoundn´t be able              
    //to press D1 (1).
    do
    {
        number2 = Console.ReadKey();
        Console.WriteLine("Number 2 was pressed");
        //This is the 2nd answer
    }
    while (number2.Key != ConsoleKey.D2);
    Console.ReadLine();
} 
4

1 回答 1

1

您的代码中的问题是您的逻辑对于您要开发的游戏是错误的。

在下面的代码中,我只使用一个 Do/while 循环来获取键,然后决定使用开关是否该键是我想要获取的键之一,如果不是,我继续循环并再次询问另一个关键。

class Program
{
    static void Main(string[] args)
    {
        bool knownKeyPressed = false;

        do
        {
            Console.WriteLine("Press 1 or 2 please...");

            ConsoleKeyInfo keyReaded = Console.ReadKey();

            switch (keyReaded.Key)
            {
                case ConsoleKey.D1: //Number 1 Key
                    Console.WriteLine("Number 1 was pressed");
                    Console.WriteLine("Question number 1");
                    knownKeyPressed = true;
                    break;

                case ConsoleKey.D2: //Number 2 Key
                    Console.WriteLine("Number 2 was pressed");
                    Console.WriteLine("Question number 2");
                    knownKeyPressed = true;
                    break;

                default: //Not known key pressed
                    Console.WriteLine("Wrong key, please try again.");
                    knownKeyPressed = false;
                    break;
            }
        } while(!knownKeyPressed);

        Console.WriteLine("Bye, bye");

        Console.ReadLine();
    }
}
于 2015-09-15T16:56:21.617 回答