2016-04-20 4 views
1

Мне нужно ввести конкретные ключи (стрелки.left и стрелки.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(). Является ли это возможным?

+1

Возможный дубликат [Прислушайтесь нажатиями клавиши в консольном приложении .NET] (http://stackoverflow.com/questions/5891538/listen-for-key-press-in-net-console-app) –

+0

'if (Console.KeyAvailable) {char key = Console.ReadKey (false);}'? –

ответ

0

Как указано RB, вы можете настроить слушателя для нажатия клавиши вместо этого, и проверьте, верно ли, чтобы они вам сбросить нажатие клавиши обнулить и переместить автомобиль в этом направлении

Listen for key press in .NET console app

0

другой возможным обходным путем является использование 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 
     } 

    } 
} 
Смежные вопросы