2012-04-19 77 views
2

我正在製作一個Seabattle遊戲,其中的船舶隱藏在具有標籤陣列的面板中。這個標籤數組需要具有更多或更少的行和列,具體取決於所選的難度級別。將面板綁定到表單

所以我做了一個新的類「Gameboard」,其中面板和標籤數組被定義。 的問題是,我無法弄清楚如何將面板讓我在這個類的窗體綁定..

namespace SO_S2_Programmeren_Groep08 { 
class GameBoard{ 

Panel pnlSlagveld; 
private Label[,] lblArray; 
private int row; 
private int column;  

public Label[,] LblArray { 
    get { 
    return lblArray; 
    } 
    set { 
    lblArray = value; 
    } 
} 

public int Row { 
    get { return row; } 
    set { row = value; } 
} 

public int Column { 
    get { return column; } 
    set { column = value; } 
} 

public GameBoard(int row, int column) { 
    this.row = row; 
    this.column = column; 
    CreateLableArray(row, column); 
} 

public GameBoard() { 
    this.row = 7; 
    this.column = 9; 
    CreateLableArray(row, column); 
} 

private void CreateLableArray(int ingrow, int ingcolumn) { 
    pnlBattleField = new System.Windows.Forms.Panel(); 
    lblArray = new Label[ingrow, ingcolumn]; 
    int xpos = 0; 
    int ypos = 0; 

    for (int row = 0; row < ingrow; row++) { 

    for (int column = 0; column < ingcolumn; column++) { 
     lblArray[row, column] = new Label(); 
     lblArray[row, column].Left = xpos; 
     lblArray[row, column].Top = ypos; 
     lblArray[row, column].Width = 50; 
     lblArray[row, column].Height = 50; 

     lblArray[row, column].Tag = (char)('A' + column) + (row + 1).ToString(); 
     lblArray[row, column].Click += lblArray_Click; 
     lblArray[row, column].BackColor = Color.Aqua; 
     lblArray[row, column].BorderStyle = BorderStyle.FixedSingle; 

     pnlBattlefield.Controls.Add(lblArray[row, column]); 

     xpos += lblArray[row, column].Width; 
    } 
    ypos += lblArray[row, 0].Width; 
    xpos = 0; 
    } 
}/*CreateLableArray*/ 

private void lblArray_Click(object sender, EventArgs e) { 
    MessageBox.Show("Clicked on Label " + ((Label)sender).Tag.ToString()); 
} 

} 

}

如果你想看到更多的類請諮詢!

謝謝!

+0

請問您可以向我展示將面板添加到表單的代碼行嗎?我不習慣使用Windows窗體應用程序:/ – David 2012-04-19 14:14:20

+0

'Form someform = ...; someForm.Controls.Add(somePanel);'但你可能不想這樣做,你想重新調整你的程序一點點。 – Servy 2012-04-19 14:15:46

回答

0

你可以執行下列操作之一:

  1. 使「遊戲鍵盤」形式,然後將面板添加到該表單。如果你想這樣做,我會建議創建一個Windows窗體項目(如果你還沒有),並將此代碼添加到主窗體(或添加的新窗體)的代碼中,以便擁有設計器組件和所有的窗體的視覺工作室功能。

  2. 使其成爲usercontrol並將該usercontrol添加到窗體。如果你想這樣做,我會爲項目添加一個新的用戶控件,並再次將該代碼添加到該用戶控件中,以便獲得visual studio支持。

  3. 在您的遊戲板內創建一個new Form()並將其添加到該文件中。 (這與winforms中的標準形式實踐相反,並且你不會得到儘可能多的IDE幫助,所以我不會爲新程序員提出這個建議)。

+0

謝謝! 我想在另一個類中定義面板的原因是Form.cs已經有很多代碼(船隻必須隨機放置在labelarray上) 所以也許最好是移動代碼到另一個類而不是「GameBoard」 – David 2012-04-19 14:19:08

+0

@David這就是爲什麼我有點#2,這聽起來像是最適合你的。這可以被認爲是與表單其餘部分分離的複雜「組件」,並且可以添加到該表單中。當然你可以進入窗體控件,並確實做一個'Controls.Add(somePanel)'。 – Servy 2012-04-19 14:20:47

+0

非常感謝! 我想我已經想通了..並且這將會是容易的部分:) – David 2012-04-19 14:37:19