2012-07-04 46 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");