2015-08-08 106 views
2

我創建了一個控制檯遊戲,就像「我生成一個隨機數,找到它」一樣簡單,但有很多選項。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。

+0

可能重複[如何添加超時到Console.ReadLine()?](http://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline) – Amit

+0

我讀過這個話題,實際上這裏的超時只是用戶輸入並不是所有的流程,驗證等。 –

+0

這就是你遇到問題的地方。你自己說過:*但是如果控制檯要求輸入數字(Console.ReadLine())*,線程不會中斷。使用該答案中的信息來解決您的問題。 – Amit

回答

0

也許你正在尋找一個計時器?你可以註冊一個事件,這個事件會在90秒後觸發,在循環發生時運行。文檔可以在這裏找到:Timer class MSDN documentation

我相信用法是:

Timer timer = new Timer { Interval = new Timespan (0,1,30); 
timer.elapsed += //function to fire to kill the app or the game 
+0

我會研究它,謝謝一堆。如果它能奏效,我會給出新聞。 –

0

You'd need to make each console read with a timeout equal to the amount of time left in the game.這解決了這個問題。

然後,您需要一種方式來指示timerb線程在主遊戲循環結束時關閉。我認爲最簡單的方法是在剩餘時間爲< = 0時結束遊戲循環。或者,你可以讓timerb主線程在t == 0時關閉。不過,線程間通信總是很複雜且容易出錯。

您可以通過設置volatile bool shutdowntrue並讓timerb輪詢該變量並自行關閉來發信號通知timerb線程關閉。