程序仍在运行时的用户输入 [英] User input while program still running
问题描述
我正在做一个乒乓球比赛. 除了用户移动拨片外,我一切正常.我正在使用一个while(true)循环,其中调用了所有方法.如何使用WASD移动拨片?我希望程序在等待用户输入时继续运行.我尝试使用Console.ReadKey(),但它冻结了程序
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
推荐答案
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 ..
核心问题是Console.ReadKey
会阻止(或冻结"),直到可以读取密钥为止.使用 Console.KeyAvailable 来查看当前是否有密钥可用:
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);
}
这篇关于程序仍在运行时的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!