2017-09-25 65 views
0

我一直在尝试做一个扫雷游戏,给出单元格的坐标,它会递归地揭示相邻的单元格,直到找到与炸弹相邻的单元格。我有一个方法,给定坐标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); 
    } 
} 

对于每个位置,但无济于事。任何指针将不胜感激。

+1

你试过的递归行为是什么?它有什么问题? – Tyler

+0

不相关:节省自己很多努力,并在开始时计算每个网格坐标的矿场数。它应该让你大幅削减这个逻辑,并使你更容易发现你的bug /解决方案。 – user4581301

回答

0

递归不应该是执行排雷计数本身的代码的一部分。它应该是负责揭示附近瓷砖的功能的一部分。

int get_adjacent_mine_count(point p) { 
    int mine_count = 0; 
    for(int i = -1; i <= 1; i++) { 
     for(int j = -1; j <= 1; j++) { 
      point this_point(p.x + i, p.y + j); 
      //is_inside_board checks to see if the point's coordinates are less than 0 
      //or greater than the board size 
      if(!is_inside_board(board, this_point)) continue; 
      //We ignore the center tile 
      if(i == 0 && j == 0) continue; 

      if(board(this_point).hasMine) 
       mine_count++; 
     } 
    } 
    return mine_count; 
} 

void reveal_tiles(point p) { 
    //We shouldn't throw if the recursion is correct 
    if(board(p).hasMine) throw Explosion("Stepped on a Mine!"); 
    //Single call to previously defined function 
    int num_of_adjacent_mines = get_adjacent_mine_count(p); 
    //I'm assuming this gets initialized to -1 beforehand 
    board(p).revealed = num_of_adjacent_mines; 
    if(num_of_adjacent_mines == 0) { 
     for(int i = -1; i <= 1; i++) { 
      for(int j = -1; j <= 1; j++) { 
       point this_point(p.x + i, p.y + j); 
       if(!is_inside_board(board, this_point)) continue; 
       if(i == 0 && j == 0) continue; 
       if(board(this_point).revealed == -1) 
        reveal_tiles(this_point); 
      } 
     } 
    } 
} 

我会强烈建议你写一个简单的Matrix类来表示board,其中我的代码意味着你这样做,因为这是不是只是想用一个二维数组进行交互的更强大的解决方案C风格的方式,你这样做。