我使用了兩個同時運行的線程,一個線程用於顯示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();
}
您需要重置光標移動到你在't1'來的地方。 – thst
你的意思是,在「Console.Write(」timeleft:{0}「,t);」add「Console.SetCursorPosition(10,1);」right? – howtocode
是的,這就是我的建議,但如果輸入不止一個字符,它不會解決您的問題。當你使用'readline'時,用戶可以輸入多個字符,但只要't1'結束,光標就會跳轉到第一個字符位置。 – thst