我的逻辑错误,无法弄清楚它是什么.基本上,我不断计算游戏循环的每次迭代的时间跨度,并将该持续时间添加到之前的持续时间.我正在尝试计算游戏的总时间.当然,它不会产生正确的结果.我究竟做错了什么?非常感谢任何指导.
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();
}
Run Code Online (Sandbox Code Playgroud)
而不是时间跨度,使用StopWatch类来计算经过的时间:
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Do stuff ...
stopWatch.Stop();
Run Code Online (Sandbox Code Playgroud)