2010-11-26 67 views
3

我在邏輯中遇到錯誤,無法弄清楚它是什麼。基本上,我不斷計算遊戲循環的每次迭代的時間跨度,並將該持續時間添加到之前的持續時間。我正在計算遊戲的總時間。當然,它不會產生正確的結果。我究竟做錯了什麼?任何指導非常感謝。時間範圍邏輯錯誤

 private TimeSpan totalDuration = TimeSpan.FromSeconds(1); 
     private int score = 0; 

     public void Stop() 
     { 
      IsGameOver = true; 
      //MessageBox.Show(String.Format("Game Over\n\nScore = {0}", score)); 
      MessageBox.Show(String.Format("Game Over\n\nScore = {0}\n\nTime 
      Duration={1}", score, totalDuration)); 
      Application.Exit(); 
     } 

     public void Start() 
     { 

      score = 0; 
      IsGameOver = false; 

      currentRedLightX = 0; 
      currentRedLightY = 0; 

      currentGreenLightX = width/2; 
      currentGreenLightY = height/2; 


      double minIterationDuration = SPEED; // 50 frames/sec 

      //game loop 
      while (!IsGameOver) 
     { 
      if (IsCollision()) 
      { 
       score += 10; 
      } 

      DateTime startIterationTime = System.DateTime.UtcNow; 
      UpdateGameState(); 
      Render(); 
      DateTime endIterationTime = System.DateTime.UtcNow; 
      TimeSpan iterationDuration = endIterationTime - startIterationTime; 
      totalDuration += iterationDuration; 
      //totalDuration += iterationDuration.Duration();     
      if (iterationDuration.TotalMilliseconds < minIterationDuration) 
       Thread.Sleep(Convert.ToInt32(minIterationDuration - 
       iterationDuration.TotalMilliseconds)); 

      Application.DoEvents(); 
     } 

回答

1

您不會在您的計時中包含發生在您的DoEvents通話中的任何事情 - 所以您不會捕獲遊戲運行的所有時間。

如果你正在做的只是顯示總的持續時間,爲什麼不直接使用遊戲的開始和結束時間呢,而不是總結所有的微小間隔呢?

+0

聽起來不錯,但我該怎麼做? – Mike 2010-11-26 15:28:47

5

取而代之的時間跨度中,使用StopWatch類來計算經過時間:

Stopwatch stopWatch = new Stopwatch(); 
stopWatch.Start(); 
// Do stuff ... 
stopWatch.Stop(); 
1

DateTime.UtcNow將具有相對較低的精度。假設你的循環速度相當快,我不會驚訝地發現大多數時間,iterationDuration實際上是零 - 導致不正確的結果。這就是爲什麼使用Stopwatch(反覆使用同一個,恰當地調用Start/Stop但不是Reset)是更好的方法。 Stopwatch將使用高分辨率系統定時器(如果有)。

順便說一句,在UI線程中睡覺並使用Application.DoEvents在UI編程方面是非常討厭的。我想知道如果你真的想要一個Timer而不是...

1

我想你的邏輯中缺少的東西是考慮到你發送線程睡覺的時間。您可能希望在將它發送到睡眠之前或之後添加該時間。

+0

我看到了Oded的答案,即使你使用StopWatch類,如果你開始和停止它,並且不包括線程睡着的時間,它將不會計算遊戲總時間,如果沒有在你的正確時間使用循環。 – 2010-11-26 15:27:39