0

I want to replace button location (Interchange location )by black button when i click it and it is next to black button (b9=black button and lable1 is a temp for saving location).

I made this method :

void checkLocation()
    {
        if (ActiveControl.Location == new Point(5, 7))//-----------for button 1
        {
            if (b9.Location == new Point(83, 7) || b9.Location == new Point(5, 71))
            {
                label1.Location = ActiveControl.Location;
                ActiveControl.Location = b9.Location;
                b9.Location = label1.Location;
            }
        }// it continue for every button

and I write this code for every button_click

private void button1_Click(object sender, EventArgs e)
    {
       checkLocation();
    }

now,some button don't work currently . what is wrong ?

4

2 回答 2

1

感谢 pswg 我认为它更短更合适:

void swapLocation()
    {
        var tmp = ActiveControl.Location;

        if((ActiveControl.Location.X==b9.Location.X)&&(Math.Abs(b9.Location.Y-ActiveControl.Location.Y)<=60))
            {
             ActiveControl.Location = b9.Location;
             b9.Location = tmp;
            }
        if ((ActiveControl.Location.Y == b9.Location.Y) && (Math.Abs(b9.Location.X-ActiveControl.Location.X) <= 70))
            {
            ActiveControl.Location = b9.Location;
            b9.Location = tmp;
            }
        }
于 2013-06-04T09:14:07.880 回答
0

只需执行此操作即可交换两个控件的位置:

void swapLocation()
{
    var tmp = ActiveControl.Location;
    ActiveControl.Location = b9.Location;
    b9.Location = tmp;
}

或更一般地说

void swapLocation(Control x, Control y)
{
    var tmp = x.Location;
    x.Location = y.Location;
    y.Location = tmp;
}

...
swapLocation(ActiveControl, b9);

更新

看起来您正在尝试实现15-puzzle的一个版本。有很多方法可以解决这个问题,但为了避免彻底重写你的程序,我建议这样做:

private int buttonWidth = 82;
private int buttonHeight = 82; // adjust these values as needed

private void button_Click(object sender, EventArgs e)
{
   if ((Math.Abs(ActiveControl.Location.X - b9.Location.X) == 0 &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == buttonHeight) ||
       (Math.Abs(ActiveControl.Location.X - b9.Location.X) == buttonWidth &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == 0))
   {
       swapLocation(ActiveControl, b9);
   }
}

这基本上是检查 是否在 的ActiveControl正上方、下方、左侧或右侧b9,如果是,则交换它们。您可以将此单击处理程序用于所有按钮 1 到 8。请注意,此方法适用于具有固定宽度和高度的按钮。

于 2013-06-03T16:47:56.583 回答