2012-07-04 45 views
0

我是C#的初學者。我正在開發一個控制檯遊戲,並且我在C#中的Thread中遇到了問題。如何在C#中用Console.Clear()和多線程進行倒計時

我的遊戲將顯示倒數計時器運行的頂部欄。我嘗試使用一個線程,我使用Console.Clear()清除舊號碼,然後在一行上替換爲新號碼(59,58,57 ...)。我的遊戲在用戶輸入用戶在中心屏幕或任何地方的數據時顯示一條消息,等等。但是,當我開始線程倒計時時,它清除了控制檯屏幕,並且清除了用戶可以輸入用戶數據的消息。你能幫我解釋一下如何開始2個線程,做更多不同的任務嗎?

using System; using System.Threading; 
namespace ConsoleApplication1 { 
    class Program { 
    static void Main(string[] args) { 
     Program m = new Program(); 
     Thread pCountDown = new Thread(new ThreadStart(
      m.DisplayCountDown 
     )); 
     Thread pDisplayForm = new Thread(new ThreadStart(
      m.DisplayForm  
     )); 
     pCountDown.Start(); 
     pDisplayForm.Start(); 
     Console.ReadKey(); 
    } 

    private void DisplayCountDown() { 
     for (int i = 60; i >= 0; --i) { 
      Console.Write("Time: {0}",i); 
      Thread.Sleep(1000); 
      Console.Clear(); 
     } 

    } 

    private void DisplayForm() { 
     while (true) { 
      Console.Write("Enter your number: "); 
      int a = Int32.Parse(Console.ReadLine()); 
      Console.WriteLine(a); 
      Console.ReadLine(); 
     } 
    } 
} 
} 

錯誤: My error

我想是這樣的:

圖片(對不起,我是一個新的成員):Like this

+0

我肯定在控制檯顯示的專家,所以希望有人有更好的建議。但看起來你至少需要在每個倒計時步驟重新繪製整個屏幕,而不僅僅是計時器。即使這樣,你也會遇到每秒清除用戶輸入的問題(或者至少是他們輸入的可見性,這可能導致一個單獨的UX)。我不確定是否有辦法清除控制檯的部分內容以清除... – David

回答

1

你不需要線程也不明確控制檯。根據建議here,只需使用Console.SetCursorPosition()Console.Write(),這樣您就可以覆蓋該號碼。

+0

謝謝!我已完成! –

0

下面是一個示例DisplayCountDown不清除整個屏幕每秒鐘:

private void DisplayCountDown() 
{ 
    for (int i = 20; i >= 0; --i) 
    { 
     int l = Console.CursorLeft; 
     int t = Console.CursorTop; 
     Console.CursorLeft = 0; 
     Console.CursorTop = 0; 
     Console.Write("Time: {0} ", i); 
     Console.CursorLeft = l; 
     Console.CursorTop = t; 
     Thread.Sleep(1000); 
    } 
} 

然而,這仍然留下一些問題。以我爲例,我看到「輸入你的號碼」出現在頂線和被覆蓋,所以不得不增加一行

if (Console.CursorTop == 0) Console.CursorTop = 1; 

while循環中。另外,如果用戶輸入了足夠的數字,倒計數將滾動到視圖外,如果您嘗試向上滾動查看,則會自動設置光標位置。

我也有間歇性問題,int.Parse拋出一個異常,大概是由於在用戶輸入的某個關鍵點發生倒計時引起的。

+0

謝謝!我已經完成了! –

1

您不需要清除控制檯。 Console.Write()寫入現有字符,所以只需更改光標位置Console.SetCursorPosition(x,y);

例如:

string mystring = "put what you want to right here"; 
Console.SetCursorPosition(0,0); //the position starts at 0 just make a note of it 
Conolse.Write(mystring); 

//now when you are ready to clear the text and print something over it again 
//just add this 

//now first erase the previous text 
for(int i = 0; i< mystring.Length; i++) 
{ 
    Console.SetCursorPosition(i,0); 
    Console.Write(' '); 
} 

//now write your new text 
mystring = "something else"; 
Console.SetCursorPosition(0,0); 
Console.Write("mystring");