我使用了两个同时运行的线程,一个线程用于显示timeleft
(倒计时从3s到0s),另一个线程用于从用户获取输入并检查输入。 / p>
这里的问题是:如何将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 :(得分:0)
设置input
:
timeleft
位置
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);
}