移动对象的C#定时器

use*_*627 0 c# animation timer ticker

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

我需要一个计时器还是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;
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

在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 ;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dmi*_*oly 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)