1. 程式人生 > >C_掃雷小遊戲當一個位置沒有雷時展開周圍八個位置

C_掃雷小遊戲當一個位置沒有雷時展開周圍八個位置

這兩天試著用C語言編寫了掃雷小遊戲

對於點開一個位置,將周圍八個位置全部展開的程式碼如下:
/—地圖更新—/
void map_update(char show_map[MAX_ROW + 2][MAX_COL + 2],
char mine_map[MAX_ROW + 2][MAX_COL + 2],
int row, int col)
{
int mine_count = 0;
/—統計(row, col)周圍八格中的地雷總數—/
mine_count = (mine_map[row - 1][col - 1] - ‘0’)
+ (mine_map[row - 1][col] - ‘0’)
+ (mine_map[row - 1][col + 1] - ‘0’)
+ (mine_map[row][col - 1] - ‘0’)
+ (mine_map[row][col + 1] - ‘0’)
+ (mine_map[row + 1][col - 1] - ‘0’)
+ (mine_map[row + 1][col] - ‘0’)
+ (mine_map[row + 1][col + 1] - ‘0’);
show_map[row][col] = mine_count + ‘0’;
blank_count++;
/—(row, col)周圍展開—

/
if (show_map[row][col] == ‘0’)
{
/—當(row, col)為0時,遍歷周圍8個位置—/
for (int i = row - 1; i <= row + 1; i++)
{
/—橫座標越界判斷—/
if (i < 1 || i > MAX_ROW)
{
continue;
}
for (int j = col - 1; j <= col + 1; j++)
{
/—縱座標越界判斷—/
if (j < 1 || j > MAX_COL)
{
continue;
}
/—跳過(row, col)位置—/
else if (i == row && j == col)
{
continue;
}
else
{
/—若該位置還未被翻開,則遞迴呼叫—
/
if (show_map[i][j] == ‘*’)
{
map_update(show_map, mine_map, i, j);
}
}
}
}
}
}

該方案使用遞迴呼叫的方法,對翻開為0的位置,遍歷周圍八個位置,統計其雷的數量,如果為0,重複上述操作