繁体   English   中英

用于移动对象的C#计时器

[英]C# timers for moving objects

我有4只正在比赛的狗,我需要将它们移动通过表格,但它们不会逐渐移动,它们从起跑线开始,然后立即传送到终点线,而不会在两者之间移动。 随着每个计时器的滴答声,它们的location.X会增加。

我需要一个计时器还是四个计时器? 我目前有一个,它的间隔设置为400。

这是相关代码:

private void btnRace_Click(object sender, EventArgs e)
{   
    btnBet.Enabled = false;
    timer1.Stop();
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{   while (!isWon)
    {
        for (i = 0; i < Dogs.Length; i++) // there are four dogs
        {                    
            if (Dogs[i].Run()) // Run() returns true if full racetrack is covered by this dog
            {
                Winner = i + 1;
                isWon = true;

                MessageBox.Show("We have a winner! Dog #" + Winner);

                break;
            }
        }
}

在Dog类中:

public bool Run()
{               
    Distance = 10 + Randomizer.Next(1, 4);
    p = this.myPictureBox.Location;
    p.X += Distance ;            
    this.myPictureBox.Location = p;

    //return true if I won the game
    if (p.X >= raceTrackLength)
    {
        return true ;
    }
    else
    {
        return false ;
    }
}

狗似乎只向前移动了一步,然后立即出现在终点线上。 我究竟做错了什么?

从timer1_Tick方法中删除While循环。 此方法每400毫秒运行一次,但在您的情况下,首次启动时将等待直到一只狗获胜。

另外,您应该在一只狗获胜后停止计时器。

private void timer1_Tick(object sender, EventArgs e)
{   
    for (i = 0; i < Dogs.Length; i++) // there are four dogs
    {                    
        if (Dogs[i].Run()) // Run() returns true if full racetrack is covered by this dog
        {
            Winner = i + 1;
            isWon = true;
            timer1.Stop();
            MessageBox.Show("We have a winner! Dog #" + Winner);
            break;
        }
    }
}

您的计时器仅关闭一次并停留在此循环中;

  while (!isWon)
  {
  }

删除循环,让Timer完成工作

最后添加

 if (isWon) timer1.Stop();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM