I have an error in my logic and am having trouble figuring out what it is. Basically, I continuously calculate the time span of each iteration of the gaming loop and add that duration to the duration before it. I am trying to calculate the total time the game is played. Of course, it doesn’t produce the right results. What am I doing wrong? Any guidance is greatly 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();
}
You’re not including in your timing anything that happens in your
DoEventscall – so you’re not going to capture all of the time the game’s running.If all you’re doing is displaying the total duration, why not just use the start and end time of the game for that, instead of summing all of the tiny intervals inbetween?