所以,我试图做的是制作一个按钮数组,但只有按钮出现在先前确定的数组中。我不太擅长解释,所以生病了直观表达我的意思。
我理解它看起来很简单,并且我在5分钟内把它放在一起,但我希望它能够实现我想要制作的东西。我只是不知道如何做到这一点。 方块应该代表按钮。我试图在Visual Studio中创建他。
这是迄今为止我所得到的:
private void Form1_Load(object sender, EventArgs e)
{
Marble();
}
public void Marble()
{
int ButtonWidth = 40;
int ButtonHeight = 40;
int Distance = 20;
int start_x = 10;
int start_y = 10;
int y = 0;
int x = 0;
int delX = x + (y * 2);
for (x = 0; x < 8; x++)
{
for (y = 0; y < 8; y++)
{
GameButton tmpButton = new GameButton();
tmpButton.BackColor = Color.Black;
tmpButton.Top = start_x + (x * ButtonHeight + Distance);
tmpButton.Left = start_y + (y * ButtonWidth + Distance);
tmpButton.Width = ButtonWidth;
tmpButton.Height = ButtonHeight;
tmpButton.Text = "X: " + x.ToString() + " Y: " + y.ToString();
tmpButton.MouseUp += TmpButton_MouseUp;
tmpButton.Row = x;
tmpButton.Column = y;
tmpButton.Currentcolor = false;
if (x == 4 && y == 6) {
tmpButton.BackColor = Color.White;
}
else
{
this.Controls.Add(tmpButton);
}
}
}
}
private void TmpButton_MouseUp(object sender, MouseEventArgs e)
{
GameButton Mygamebutton = (GameButton) sender;
Mygamebutton.Currentcolor = !Mygamebutton.Currentcolor;
if (Mygamebutton.Currentcolor == true)
{
Mygamebutton.BackColor = Color.Black;
}
else
{
Mygamebutton.BackColor = Color.White;
}
}
}
答案 0 :(得分:0)
我会使用相同大小的数组的TableLayoutPanel
控件来攻击此请求。
您将必须使用for
(或嵌套for)结构来循环所有数组位置,如果在该位置内您拥有所需的值,则在{{1的相同位置内创建一个Button }}
如果您不了解TableLayoutPanel
控件:https://msdn.microsoft.com/en-us/library/dd492143.aspx
答案 1 :(得分:0)
首先创建所有按钮:
const int BUTTON_SIZE = 40;
int W = ParentPanel.Width / BUTTON_SIZE;
int H = ParentPanel.Height / BUTTON_SIZE;
for (int x = 0; x < W; x++ )
{
for(int y = 0; y < H; y++)
{
Button btn = new Button();
btn.Name = "button_" + x.ToString() + "_" + y.ToString();
btn.Size = new Size(BUTTON_SIZE, BUTTON_SIZE);
btn.Location = new Point(BUTTON_SIZE * x, BUTTON_SIZE * y);
ParentPanel.Controls.Add(btn);
}
}
正如您所注意到的按钮被命名为button_0_1
,button_0_2
等。
现在你所要做的就是打个简单的电话:
for(int x = 0; x < W; x++)
{
for(int y = 0; y < H; y++)
{
Button btn = ParentPanel.Controls.OfType<Button>().FirstOrDefault(ctrl => ctrl.Name == "button_" + x.ToString() + "_" + y.ToString());
if(btn != null)
{
// depending on if arr[x][y] == 1 make your action
}
}
}