是否可以使用某些控件制作矩阵并在矩阵中对其进行修改?
例如,我们可以看一下扫雷游戏。如果所有按钮都是动态创建的,则将它们插入this.Controls中(仅在这种情况下)。炸弹随机放置在某些按钮上,而我需要在其他按钮上放置与炸弹周围的炸弹数量相等的数字。
因此,仅使用列表,就很难实现这一目标。使用矩阵,沿着X和Y的方向(8个方向)查找炸弹会更容易。有没有办法简化这个问题?
我不知道某些代码是否会有所帮助,但我将展示到目前为止所做的事情。
private bool[] bombs = new bool[400];
private int counter = 1;
private int bombsFound = 0;
private Point p = new Point(0, 0);
private void GenerateMineSweeper()
{
for (int i = 1; i <= 15; ++i)
{
for (int j = 1; j <= 25; ++j)
{
Button box = new Button();
box.Location = p;
box.Size = new Size(25, 25);
box.BackColor = Color.RoyalBlue;
box.Padding = new Padding(0);
box.FlatStyle = FlatStyle.Popup;
box.Click += new EventHandler(box_Click);
this.Controls.Add(box);
bombs[counter++] = false;
p.X += 23;
}
p.Y += 23;
p.X = 0;
}
counter = 0;
}
private void GenerateBombsLocations()
{
// For 15*25 = 375 boxes will be set 75 bombs
Random rand = new Random();
int j;
for (int i = 1; i <= 75; i++)
{
j = rand.Next(1, 375);
while (bombs[j] == true)
{
j = rand.Next(1, 375);
}
bombs[j] = true; // Add bomb
counter = i;
}
lbl_bombsTotal.Text = counter.ToString();
counter = 0;
}
protected void box_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
var indexOfThisButton = this.Controls.IndexOf(btn);
if (bombs[indexOfThisButton] == true)
{
btn.BackgroundImageLayout = ImageLayout.Stretch;
btn.BackgroundImage = Image.FromFile(Application.StartupPath + @"\bomb.jpg");
bombsFound++;
lbl_bmbFound.Text = bombsFound.ToString();
}
else
{
btn.Enabled = false;
btn.BackColor = Color.LightGray;
int i = BombsAround(indexOfThisButton); // find how many bombs are around
btn.Text = i.ToString();
}
}
private int BombsAround(int index)
{
int bombs = 0;
// find bombs
return bombs;
}