控制台特定按键输入,无阻塞
本文关键字:输入 控制台 | 更新日期: 2024-10-21 13:06:34
我需要在控制台应用程序中输入特定的键(arrows.left和arrows.right),而不阻塞循环。
这是代码:
while (fuel>0) {
moveAndGenerate();
for (int i=0;i<road.GetLength(0); i++)
{
for (int j = 0; j < road.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", road[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("Paliwo: "+ (fuel=fuel-5) + "%");
moveAndGenerate();
replaceArrays();
Thread.Sleep(1000);
Console.Clear();
}
它生成了一个简单的游戏:
| :x|
| : |
|x: |
| :↑|
只要有燃料就在回路内。我希望箭头在不等待Console.ReadKey()
的情况下向右/向左移动。有可能吗?
正如RB所说,你可以为按键设置一个监听器,并检查是否为true,如果是这样,你可以将按键重置为null,并将汽车向该方向移动
在.NET控制台应用程序中收听按键
另一种可能的解决方法是使用BackgroundWorker
来侦听输入。通过这种方式,您可以同时处理用户输入和主代码。它类似于一个单独的线程。
您需要将using System.ComponentModel;
添加到您的程序中。
static BackgroundWorker backgroundWorker1 = new BackgroundWorker(); // Create the background worker
static string input = ""; // where the user command is stored
public static void Main()
{
// All the code preceding the main while loop is here
// Variable declarations etc.
//Setup a background worker
backgroundWorker1.DoWork += BackgroundWorker1_DoWork; // This tells the worker what to do once it starts working
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted; // This tells the worker what to do once its task is completed
backgroundWorker1.RunWorkerAsync(); // This starts the background worker
// Your main loop
while (fuel>0)
{
moveAndGenerate();
for (int i=0;i<road.GetLength(0); i++)
{
for (int j = 0; j < road.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", road[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("Paliwo: "+ (fuel=fuel-5) + "%");
moveAndGenerate();
replaceArrays();
Thread.Sleep(1000);
Console.Clear();
}
// This is what the background worker will do in the background
private static void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (Console.KeyAvailable == false)
{
System.Threading.Thread.Sleep(100); // prevent the thread from eating too much CPU time
}
else
{
input = Console.In.ReadLine();
// Do stuff with input here or, since you can make it a static
// variable, do stuff with it in the while loop.
}
}
// This is what will happen when the worker completes reading
// a user input; since its task was completed, it will need to restart
private static void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs
{
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync(); // restart the worker
}
}
}