控制台上的 2 个关键选择

2 key choices on console

我正在 Visual Studio 上使用 C#(在控制台中)制作游戏。这是关于对话的,你可以用 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();
} 

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

在下面的代码中,我只使用一个 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();
    }
}