Search code examples
c#keyboardconsole-applicationgame-development

Alternate between Console.ReadKey() and Thread.Sleep()


I'm making a game in c# in the console, and I want to make frames, I am trying to alternate between Console.ReadKey() and Thread.Sleep(100), to make at least 5 frames per second, 100 millisecs for thread.Sleep and another 100 millisecs as a window for the user to press a key like WASD for movements, I want to achieve the frame updates even if the player don't make any input

So, if there's a way to wait only 100 millisecs for the input and the cut the opportunity and continue with the program, it would be awesome if you let me know

I tried to make a game but it the frame only refreshes if the player press a key, so if you don't touch the keyboard, the game will stand still, nothing can move because the program is waiting for a user input and that's not what I want.


Solution

  • I think your best approach here is to wait a given amount of time, and then take the inputs after that time, and act accordingly. The code below will wait 200ms, then do something with all of the inputs entered during that 200ms, and then run your normal program code.

    By using Console.KeyAvailable, we can check if there is a key for us to read. This will avoid the program stopping and waiting for the user to enter something. Meaning, if the user enters nothing, the program will move on and do your other logic.

    You can also use Console.ReadKey(true) to hide the character typed from the user, if you desire.

    while(true)
    {
        // wait
        Thread.Sleep(200);
    
        // get keys pressed while waiting
        while(Console.KeyAvailable)
        {
            ConsoleKeyInfo key = Console.ReadKey(true);
            switch(key.Key)
            {
                // do whatever with the keys you want to do here
                case ConsoleKey.Enter:
                    return; // quit on enter
                default:
                    Console.WriteLine(key.Key);
                    break;
            }
        }
    
        // ...program code...
        Console.WriteLine("frame");
    }