Search code examples
c#console

Console.KeyAvailable doesn't detect the key


I'm trying to make a simple snake game in console (without eating something, only snake moving around) but when I press UpArrow, it doesn't do anything. I also tried W but it writes w to console instead.

Code:

while(Console.KeyAvailable == true)
{
    if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.UpArrow)
    {
        Console.SetCursorPosition(x, y);
        Console.WriteLine("*");
        Console.WriteLine("*");
        Console.WriteLine("*");
        x++;
        Console.WriteLine(x);
    }
}

Console.ReadLine();

Solution

  • Remove Console.KeyAvalible - both. Your program passes the loop and goes to ReadLine immediatly.

    Should look like this:

    while(Console.ReadKey(true).Key == ConsoleKey.UpArrow)
    {
    //code here-
    }