2017-09-25 55 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風格的方式,你這樣做。