0

I am making a super simple jumping over obstacles game all in the terminal, similar to the google no internet dinosaur game. The ground moves towards the player and when an obstacle comes I want to be able to jump over it with the press of the spacebar.
My question is how do I have my program listen for a key press without using a Readline which will pause the program and wait for an input?
I have tried using console.keyavaliable but as soon as a key is pressed it stays true, it would be easy if I was able to reset console.keyavaliable back to false every loop.
Thanks for any help.

Jameson
  • 57
  • 5
  • Thanks but this doesn't help. I tried using Console.ReadKey(true); as well but that also pauses the program and waits for an input. – Jameson Feb 23 '23 at 08:56
  • Have you also tried to check `Console.KeyAvailable` to find out if there's anything to read before reading `Console.ReadKey()` as recommended in mentioned answer? – Quercus Feb 23 '23 at 09:34
  • https://learn.microsoft.com/en-us/dotnet/api/system.console.keyavailable?redirectedfrom=MSDN&view=net-7.0#System_Console_KeyAvailable `Console.KeyAvailable` indicates that there is a keycode in the input buffer. To reset it you need to read the key via `Console.ReadKey()` so @Kamil 's suggestion is correct, just try the full code sample (Console.KeyAvailable + ReadKey after it) – rum Feb 23 '23 at 09:34

1 Answers1

0

Try this code:

private static void Main(string[] args)
{
    Task.Run(() =>
    {
        ConsoleKeyInfo keyinfo;

        do
        {
            keyinfo = Console.ReadKey();
            Console.WriteLine(keyinfo.Key + " was pressed");
        }
        while (keyinfo.Key != ConsoleKey.X);


    });

    while (true)
    {
        //Console.WriteLine("This is a while loop");
    }
}

For more information go through the following article: How to handle key press event in console application

Safee
  • 58
  • 4