Question

I'm making a pong game. I got everything working but the user moving the paddle. I am using a while (true) loop in which all the methods are invoked. How can I move the paddle with WASD? I want the program to keep going while waiting for user input. I tried using Console.ReadKey() but it freezes the program

Was it helpful?

Solution

While I would suggest using a game library (although I can't find any specifically for a terminal there is Curses Sharp which might be useful), this can be done manually ..

The core issue is that Console.ReadKey blocks (or "freezes") until a key is available to read; use Console.KeyAvailable to see if a key is currently available:

while (true) {
   // Clear out all keys in the queue; there may be multiple (hence "while")
   while (Console.KeyAvailable) {
       // Won't block because there is a key available to read. Handle it.
       var key = Console.ReadKey(true);
       HandleKey(key);
   }
   // Do other processing ..
   ProcessGameTick();
   // .. and be sure to Yield/Sleep to prevent 100% CPU usage.
   Thread.Sleep(0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top