User input while program still running

微笑、不失礼 提交于 2019-12-06 09:51:41

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