User input while program still running

佐手、 提交于 2019-12-10 10:45:02

问题


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


回答1:


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);
}


来源:https://stackoverflow.com/questions/17257777/user-input-while-program-still-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!