2

我正在尝试编写此代码,以便在单击 start Obj from 时"FORM1"将调用此方法来使用和启用timer1.

当我单击开始按钮时,狗图片将开始移动到右侧直到到达X= 620,然后它将显示消息框" win"

但是,消息框一直显示并且在 dogpic 到达球门线后不会停止

class dog
{
    public int startpost;
    public int TrackLenght = 620;
    public PictureBox dogpic = null;
    public int Location = 0;
    public Random random=new Random();

    public void ResetStart()
    { 
        dogpic.Location = new System.Drawing.Point(40, startpost);
    }

    public bool testrun()
    {
        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
            return false;
        }
        else
        {
            MessageBox.Show(dogpic.Name + " win");

            return true;
        }
    }
}
4

4 回答 4

3
//suppose dog1 is an instance of your dog class
//here is the Tick event handler of your timer1
private void timer1_Tick(object sender, EventArgs e){
    timer1.Enable = !dog1.testrun();
}
于 2013-08-19T07:26:48.037 回答
1

获胜后尝试重置 pX。

看不到你的代码,但我认为你应该这样做:

public bool testrun()
    {

        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
           return false;
        }
        else
        {

            MessageBox.Show(dogpic.Name + " win");
            ResetStart()
            return true;
        }}}
于 2013-08-19T07:31:22.067 回答
1

单击按钮时,您应该调用 ResetStart() 函数,该函数将启用计时器并完成您的工作,并在到达终点时应禁用计时器。

class dog
{
    public int startpost;
    public int TrackLenght = 620;
    public PictureBox dogpic = null;
    public int Location = 0;
    public Random random=new Random();

    public void ResetStart()
    { 
        dogpic.Location = new System.Drawing.Point(40, startpost);
        timer.Enabled=true;
    }

    public bool testrun()
    {
        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
            return false;
        }
        else
        {
            MessageBox.Show(dogpic.Name + " win");
            timer.Enabled=false;    
            return true;
        }
    }
}

希望它会奏效。

于 2013-08-19T07:54:18.060 回答
0

您可以使用计时器。

timer.Interval=5000;
timer.Enabled=true;
MessageBox.Show(dogpic.Name + " win");

您可以将其与 tck 事件相关联。

private void timer_Tick(object sender,EventArgs evt) {
    timer.Enabled=false;
}
于 2013-08-19T07:26:34.570 回答