我正在尝试在C++上实现一个棋盘游戏,它的一些功能如下:
我有4个来源,名为Mine(M),Water(W),Food(F)和Medical Supplies(S)
资源将随机分配给董事会(我已完成)
用户将输入两个坐标,如果在这些坐标上有我的坐标,它们将会爆炸并根据它们的位置破坏它们周围的细胞.例如,如果矿井位于中间的某个地方,那么它将摧毁周围的8个单元,如果另一个矿井周围爆炸,那么另一个矿井也会爆炸.
并且有一些例外情况,例如,如果坐标位于拐角处,它将只会炸掉它周围的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?
Run Code Online (Sandbox Code Playgroud)
伪代码:
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
}
Run Code Online (Sandbox Code Playgroud)