【发布时间】:2017-09-25 20:24:26
【问题描述】:
我一直在尝试制作一个扫雷游戏,其中给定一个单元格的坐标,它将递归地显示相邻的单元格,直到找到与炸弹相邻的单元格。我有一个方法,给定坐标 x 和 y 计算它周围有多少地雷。
// Counts how many mines are adjacent to a given coordinate cell if any
void board::mineCount(int x, int y) {
// North
if (y > 0) {
if (board[x][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// South
if (y < dimensions[1] - 1) {
if (board[x][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
// East
if (x < dimensions[0] - 1) {
if (board[x + 1][y].hasMine) {
board[x][y].mineCount++;
}
}
// West
if (x > 0) {
if (board[x - 1][y].hasMine) {
board[x][y].mineCount++;
}
}
// North East
if (x < dimensions[0] - 1 && y > 0) {
if (board[x + 1][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// North West
if (x > 0 && y > 0) {
if (board[x - 1][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// South East
if (x < dimensions[0] - 1 && y < dimensions[1] - 1) {
if (board[x + 1][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
// South West
if (x > 0 && y < dimensions[1] - 1) {
if (board[x - 1][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
}
每个单元格都是一个结构体,它有一个mineCount 字段,每次在它附近发现一个地雷时,该字段就会增加1。我无法弄清楚我的递归逻辑会去哪里。我尝试做类似的事情:
// North
if (y > 0) {
if (board[x][y - 1].hasMine) {
board[x][y].mineCount++;
} else {
minecount(x, y-1);
}
}
对于每个职位,但无济于事。任何指针将不胜感激。
【问题讨论】:
-
您尝试的递归行为是什么,有什么问题?
-
不相关:节省大量精力并在开始时计算每个网格坐标的 minecount。它应该可以让你大大减少这个逻辑,让你更容易发现你的错误/解决方案。
标签: c++ multidimensional-array minesweeper