0

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();
} 
DavidG
  • 113,891
  • 12
  • 217
  • 223
N. Muñoz
  • 3
  • 2
  • use boolean variables to tell you if a button has been pressed, and if statements to see whether you should allow the button to be pressed. – user1666620 Sep 15 '15 at 16:42
  • You'll have to use Console.ReadLine() if you want to give the user a chance to correct typos. – Hans Passant Sep 15 '15 at 16:46

1 Answers1

1

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