我正在尝试在C++上实现棋盘游戏,其一些功能如下:
让我们来解决真正的问题。当我尝试实现它时,我发现实际上是大量的代码,并且我需要使其具有递归性以提供炸毁其他单元格的能力,因此对于每个可能性,我都需要检查炸毁的单元格是否是我的。有没有一种有效的方法来实现这一点,还是我只需要编写整个代码?
void explode_mines(int x,int y) {
if (x == 0 && y == 0) {
grid[0][0] = 'X';
grid[0][1] = 'X';
if (grid[0][1] == 'X') explode_mines(0, 1);
grid[1][0] = 'X';
//...
grid[1][1] = 'X';
//...
}
//Is there any efficient way?
最佳答案
伪代码:
void ExploreCell(int x, int y)
{
if (x or y are out of bounds (less than zero/greater than max))
or (this cell is a mountain, because mountains don't explode))
return
else if this location is a mine
ExplodeMine(x, y) //This cell is a mine, so it blows up again
else
DestroyCell(x, y) //This cell is a valid, non-mine target
}
void ExplodeMine(int x, int y)
{
ExploreCell(x-1, y-1);
ExploreCell(x-1, y);
....
ExploreCell(x+1, y+1);
}
void DestroyCell(int x, int y)
{
//Take care of business
}