我正在尝试在 C++ 上实现棋盘游戏,它的一些功能如下:
我有 4 个来源,分别是矿山 (M)、水 (W)、食物 (F) 和医疗用品 (S)
Sources 将随机分发到版 block (我已完成)
用户将输入两个坐标,如果这些坐标上有地雷,它们将根据位置炸毁周围的细胞。例如,如果地雷位于中间某处,它会摧毁它周围的 8 个单元格,如果在爆炸的那个单元格周围有另一个地雷,它也会使另一个单元格爆炸。
也有一些异常(exception),例如,如果坐标在拐角处,它只会炸毁它周围的 3 个单元格。
让我们来谈谈真正的问题。当我尝试实现它时,我发现它实际上是大量代码,我需要使其递归以提供炸毁其他电池的能力,因此对于每一种可能性,我都需要检查炸毁的电池是否是地雷。有没有一种有效的方法来实现它,还是我只需要编写整个代码?
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
}
关于c++ - 棋盘游戏中的递归地雷爆炸函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37398267/