我創建了一個控制檯遊戲,就像「我生成一個隨機數,找到它」一樣簡單,但有很多選項。x秒後停止循環線程方法
我當前的代碼(沒有什麼,我想在這裏)是availlable在GitHub上:https://github.com/crakmaniaque/trouvezmoi
我要的是創造我的遊戲版本將被定時,所以計算機生成號碼,用戶發現,它會產生一個新的玩家,玩家有90秒可以找到最多的隨機數。我可以很容易地編碼。
我需要幫助的是在90秒後停止遊戲(一個線程)並檢索從線程創建的答案的數量。 Console.Title
也應該顯示剩餘時間。我嘗試過的嘗試可行,但如果控制檯要求輸入號碼(Console.ReadLine()
),線程不會中斷。但是計時器是針對整個過程的,不僅僅是用戶輸入。
private static void timerb()
{
int t = 90;
for (int i = 0; i < 90; i++)
{
Console.Title = t + " seconds remaining";
Thread.Sleep(1000);
t--;
}
}
private static void cGame()
{
Thread t = new Thread(timerb);
t.Start();
while (t.IsAlive)
{
bool good = false;
int rnd = new Random().Next(0,10); // 0 and 10 are sample
while (!good)
{
try
{
Console.Write("Enter a number between x and y >");
int i = int.Parse(Console.ReadLine());
if (i == rnd)
{
good = true;
}
}
catch (FormatException)
{
Console.WriteLine("Invalid answer.");
}
}
}
}
我對線程知之甚少,在那一點上我被困住了。 有人可以幫我解決我的問題嗎?我正在使用.NET 2.0。
可能重複[如何添加超時到Console.ReadLine()?](http://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline) – Amit
我讀過這個話題,實際上這裏的超時只是用戶輸入並不是所有的流程,驗證等。 –
這就是你遇到問題的地方。你自己說過:*但是如果控制檯要求輸入數字(Console.ReadLine())*,線程不會中斷。使用該答案中的信息來解決您的問題。 – Amit