2013-06-03 106 views
0

我想用黑色按鈕代替按鈕位置(交換位置),當我點擊它並且它是黑色按鈕旁邊(b9 =黑色按鈕,lable1是保存位置的溫度)。兩個按鈕的交換位置

我做了這個方法:

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 

,我寫這篇文章的代碼爲每button_click

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

現在,一些按鈕目前沒有工作。哪裏不對 ?

+1

請爲未來的程序員着想,命名控制......然後使用該名稱來搜索控制。否則什麼「目前不工作」 – Sayse

+0

不,不,不......我不寫所有的代碼在這裏。當然,我命名我的control.all他們。 – Majid

回答

1

的感謝從p.s.w.g 我認爲這是更短的和適合:

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; 
      } 
     } 
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使用此點擊處理程序。注意此方法只有與按鈕的工作是固定的寬度和高度。

+0

我找到了我的答案,但在詢問後我不能在這裏寫8小時。現在是一個問題。在這個謎題中,我如何隨機設置按鈕? – Majid

+0

@Majid @Majid我不確定,但我相信這種謎題,如果你隨意放置按鈕,最終可能會遇到難以解決的難題。既然這個答案解決了你原來的問題,我建議你多閱讀15個難題(或者你正在研究的更小的8個難題),嘗試一下,當你遇到問題時回到這裏。哎呀,甚至有一個標籤:[標籤:8-謎題]。 –

+0

你非常幫我.tnx – Majid