我试图在 C# 中创建一个国际象棋策略应用程序。我已将面板放置在表单设计器中,它们被命名为 panel1、panel2 等......我需要知道如何将面板分配给像“chessBoardPanels [0,0]”这样的二维数组,这将允许我使用以下命令实际控制面板的背景:
chessBoardPanels[0,0].Background=Color.Black;
但它说我需要某种对象引用。
我宁愿去做这样的事情
int numBlocks = 8;
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(50, 50);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(50 * iRow, 50 * iColumn);
chessBoardPanels[iRow, iColumn] = p;
this.Controls.Add(p);
}
这将允许您动态创建面板,而无需在设计器中创建它们。
但是,您必须制定一个公式来为您处理间距。
编辑
我还添加了一个如何间隔/设置面板块的示例。
创建这样的二维数组的语法是:
Panel[,] chessBoardPanels = new Panel[8, 8];
chessBoardPanels[0, 0] = panel1;
chessBoardPanels[0, 1] = panel2;
chessBoardPanels[0, 2] = panel3;
//...
chessBoardPanels[0, 7] = panel8;
chessBoardPanels[1, 0] = panel9;
//...
我在循环中保留了一个 bool 来创建我的板,以确定是使用黑色还是白色作为背景颜色。在设置每个字段之前,您必须初始化数组(通常是二维数组):
this.Fields = new PieceButton[Board.Size, Board.Size];
board = new Board(this);
for (int i = 0; i < Board.Size; i++)
{
for (int j = 0; j < Board.Size; j++)
{
this.Fields[i, j] = new PieceButton(even ? white : black, i, j);
this.Fields[i, j].Size = fieldSize;
this.Fields[i, j].Location = new Point(
i * PieceSize + widthOffset,
(Board.Size - j - 1) * PieceSize + heightOffset);
Fields[i, j].MouseDown += this.Piece_MouseDown;
this.Controls.Add(Fields[i, j]);
even = !even;
}
even = !even;
}