N. Muñoz
N. Muñoz

Reputation: 3

2 key choices on console

I'm making a game on Visual Studio on C# (in a console). It's about dialogues, and you can answer them with 2 choices, one key (for answering the first question) is 1 and the other one is 2. The problem is that when you press one key, you can´t press the other one no more, I mean, if you press 1, you can't press 2, and vice versa.

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();
} 

Upvotes: 0

Views: 2031

Answers (1)

Ernesto Gutierrez
Ernesto Gutierrez

Reputation: 422

The problem in your code is that your logic is wrong for the game you want to develop.

In the following code I'm using just a single Do/while loop to get the keys and later decide using a switch if the key is one of the keys I want to get, if not, I continue with the loop and ask again for another key.

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();
    }
}

Upvotes: 1

Related Questions