我正在调用一个递归函数(在正方形上单击鼠标左键),但我找不到问题所在。
它应该将背景图像更改为正确的数字,将其设置为“按下”,如果它在正方形附近的地雷数量为0,它将左键单击它附近的所有正方形。
"board“是二维正方形数组(Mine类)
private void leftClick(int x, int y)
{
if (!board[x][y].pressed)
{
if (board[x][y].bomb == true)
{
board[x][y].BackgroundImage = Properties.Resources.bomb;
if (MessageBox.Show("You lost! new game?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Form.ActiveForm.Hide();
Form form2 = new MineSweeper.mainForm();
form2.ShowDialog();
}
else
Application.Exit();
}
else
{
switch (board[x][y].numOfMines)
{
case 0:
board[x][y].BackgroundImage = Properties.Resources._0;
if (x - 1 >= 0 && y - 1 >= 0 && x - 1 < row && y - 1 < column && board[x-1][y-1].pressed==false)
leftClick(x - 1, y - 1);
if (x >= 0 && y - 1 >= 0 && x < row && y - 1 < column && board[x][y - 1].pressed == false)
leftClick(x, y - 1);
if (x + 1 >= 0 && y - 1 >= 0 && x + 1 < row && y - 1 < column && board[x + 1][y - 1].pressed == false)
leftClick(x + 1, y - 1);
if (x - 1 >= 0 && y >= 0 && x - 1 < row && y < column && board[x - 1][y].pressed == false)
leftClick(x - 1, y);
if (x + 1 >= 0 && y >= 0 && x + 1 < row && y < column && board[x + 1][y].pressed == false)
leftClick(x + 1, y);
if (x - 1 >= 0 && y + 1 >= 0 && x - 1 < row && y + 1 < column && board[x - 1][y + 1].pressed == false)
leftClick(x - 1, y + 1);
if (x >= 0 && y + 1 >= 0 && x < row && y + 1 < column && board[x ][y + 1].pressed == false)
leftClick(x, y + 1);
if (x + 1 >= 0 && y + 1 >= 0 && x + 1 < row && y + 1 < column && board[x + 1][y + 1].pressed == false)
leftClick(x + 1, y + 1);
break;
case 1:
board[x][y].BackgroundImage = Properties.Resources._1;
break;
case 2:
board[x][y].BackgroundImage = Properties.Resources._2;
break;
case 3:
board[x][y].BackgroundImage = Properties.Resources._3;
break;
case 4:
board[x][y].BackgroundImage = Properties.Resources._4;
break;
case 5:
board[x][y].BackgroundImage = Properties.Resources._5;
break;
case 6:
board[x][y].BackgroundImage = Properties.Resources._6;
break;
case 7:
board[x][y].BackgroundImage = Properties.Resources._7;
break;
case 8:
board[x][y].BackgroundImage = Properties.Resources._8;
break;
}
}
board[x][y].pressed = true;
}
}发布于 2014-06-21 01:20:31
在左键单击其他矿之前设置board[x][y].pressed = true;。如果你不这样做,其他的水雷可能会再次留下原来的水雷。
if (!board[x][y].pressed)
{
board[x][y].pressed = true;
... do the other stuff here
}发布于 2014-06-21 02:12:43
除了Olivier指出的问题之外,这里还有另一个递归问题,您还没有遇到,而且几乎可以肯定在测试中也不会遇到这个问题。
if (MessageBox.Show("You lost! new game?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Form.ActiveForm.Hide();
Form form2 = new MineSweeper.mainForm();
form2.ShowDialog();
}而不是再次以相同的形式玩游戏,您正在创建一个新的表单,并且隐藏了旧的表单。虽然这每个游戏只递归一层,但它正在消耗GDI资源(它们是而不是,任何类似无限的东西,如果你泄露了它们,很容易用完),因此如果用户玩了足够多的游戏,它就会爆炸。
https://stackoverflow.com/questions/24332445
复制相似问题