I have a mistake in my logic and itβs hard for me to understand what it is. Basically, I constantly calculate the time interval of each iteration of the game loop and add this duration to the duration before it. I am trying to calculate the total playing time. Of course, this does not give the correct results. What am I doing wrong? Any recommendations are appreciated.
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();
}
source
share