移动对象的C#定时器

时间:2012-10-05 10:50:06

标签: c# animation timer ticker

我有4只狗正在比赛,我需要将它们移动到整个表格上但是它们不会逐渐移动,它们从起跑线开始并立即传送到终点线,而不会在两者之间移动。每次计时器勾选时,它们的位置都会递增。

我需要一个计时器还是4个计时器?我目前有一个,其间隔设置为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;
            }
        }
}

在狗类中:

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 ;
    }
}

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

2 个答案:

答案 0 :(得分:6)

从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;
        }
    }
}

答案 1 :(得分:1)

你的计时器只关闭了一次并且卡在这个循环中;

  while (!isWon)
  {
  }

移除循环,让定时器完成它的工作

最后添加

 if (isWon) timer1.Stop();
相关问题