NounVerber
NounVerber

Reputation: 135

Console.ReadKey not reliable

I have the following code, which waits for user input via arrow keys to move, or escape to end the program.

Console.WriteLine(startNode.Render(true));
LevelState currentNode = startNode;
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
    if (Console.ReadKey(true).Key == ConsoleKey.UpArrow)
    {
        Console.WriteLine("up");
        LevelState move = currentNode.StepInDirection(CardinalDirection.Up);
        if (move != null)
        {
            currentNode = move;
            Console.WriteLine(currentNode.Render(true));
        }
    }
    //ditto for the other 3 directions
}

However, it only occasionally acknowledges my input. If I quickly tap the escape key, for example, most of the time nothing happens. So the Console.ReadKey method seems extremely unreliable to me. What is a better alternative?

Upvotes: 0

Views: 657

Answers (1)

TheGeneral
TheGeneral

Reputation: 81473

You are calling ReadKey too many times

This is a better pattern

ConsoleKey key;
while ((key = Console.ReadKey(true).Key) != ConsoleKey.Escape)
{
   if (key == ConsoleKey.UpArrow)
   {
      ///
   }
   //ditto for the other 3 directions

}

or

// read key once
ConsoleKey key = Console.ReadKey(true).Key;
while (key != ConsoleKey.Escape)
{
   if (key == ConsoleKey.UpArrow)
   {
      ///
   }

   //ditto for the other 3 directions
   key = Console.ReadKey(true).Key;
}

Upvotes: 1

Related Questions