2015-12-30 27 views
1

我使用了兩個同時運行的線程,一個線程用於顯示timeleft(倒計數從3s到0s),另一個線程用於從用戶獲取輸入並檢查輸入。這裏如何在倒數時間運行時將光標設置爲輸入值?

問題是:如何設置cursor留在一個地方,用戶輸入的值,而Timeleft仍在每秒顯示的Console window。 (每次顯示Timeleft光標移動到另一個地方,我不能輸入值)。

Random rd = new Random(); 
     int totalscore = 0; 

     for (int i = 1; i <= 10; i++) 
     { 
      int num1 = rd.Next(50); 
      int num2 = rd.Next(50); 
      int sum = num1 + num2; 
      int input; 

      Console.SetCursorPosition(0,0); 
      Console.Write("Question {0}", i); 

      Console.SetCursorPosition(0,1); 
      Console.Write("{0} + {1}", num1, num2); 

      Console.SetCursorPosition(0, 3); 
      Console.Write("Total Score : {0}", totalscore); 

      Thread t1 = new Thread(() => 
      { 
       for (int t = 3; t > 0; t--) 
       { 
        Console.SetCursorPosition(0, 2); 
        Console.Write("timeleft : {0}", t); 
        Thread.Sleep(1000); 
       } 
      }); 
      t1.Start(); 

      Thread t2 = new Thread(() => 
      { 
       while (true) 
       { 
        Console.SetCursorPosition(10, 1); 
        input = Convert.ToInt32(Console.ReadLine()); 
        if (input == sum) 
        { 
         totalscore += 10; 
         t1.Abort(); 
         break; 
        } 
        else 
        { 
         t1.Abort(); 
         break; 
        } 
       } 
      }); 
      t2.Start(); 

      Console.SetCursorPosition(0, 3); 
      Console.WriteLine("Total score : {0}", totalscore); 

      while (true) 
      { 
       if (t1.IsAlive == false) 
       { 
        t2.Abort(); 
        break; 
       } 
      } 

      Console.Clear(); 
     } 
+0

您需要重置光標移動到你在't1'來的地方。 – thst

+0

你的意思是,在「Console.Write(」timeleft:{0}「,t);」add「Console.SetCursorPosition(10,1);」right? – howtocode

+0

是的,這就是我的建議,但如果輸入不止一個字符,它不會解決您的問題。當你使用'readline'時,用戶可以輸入多個字符,但只要't1'結束,光標就會跳轉到第一個字符位置。 – thst

回答

0

你需要設置timeleft後設置光標回input位置:

for (int t = 3; t > 0; t--) 
{ 
    Console.SetCursorPosition(0, 2); //for timer 
    Console.Write("timeleft : {0}", t); 
    Console.SetCursorPosition(10, 1); //resetting for total score 
    Thread.Sleep(1000); 
} 
+0

謝謝,有沒有辦法讓光標在任何時候都不移動,而每秒鐘仍然顯示時間左移? – howtocode

+0

不,在'控制檯'你必須改變光標的位置。你完全按照它應該做的那樣做。 – Shaharyar

相關問題