请用c语言实现扫雷程序
时间: 2024-05-17 19:18:20 浏览: 48
好的,以下是一个简单的扫雷程序的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
void print_board(char board[ROWS][COLS], int reveal_all);
void place_mines(char board[ROWS][COLS]);
int count_adjacent_mines(char board[ROWS][COLS], int row, int col);
void reveal_cell(char board[ROWS][COLS], int row, int col, int *remaining_cells);
void play_game(char board[ROWS][COLS]);
int main() {
char board[ROWS][COLS];
srand(time(NULL));
place_mines(board);
print_board(board, 0);
play_game(board);
return 0;
}
void print_board(char board[ROWS][COLS], int reveal_all) {
int i, j;
printf(" ");
for (i = 0; i < COLS; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%c ", 'A' + i);
for (j = 0; j < COLS; j++) {
if (board[i][j] == '*' && !reveal_all) {
printf(". ");
} else {
printf("%c ", board[i][j]);
}
}
printf("\n");
}
}
void place_mines(char board[ROWS][COLS]) {
int i, j, count = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = '.';
}
}
while (count < MINES) {
i = rand() % ROWS;
j = rand() % COLS;
if (board[i][j] == '.') {
board[i][j] = '*';
count++;
}
}
}
int count_adjacent_mines(char board[ROWS][COLS], int row, int col) {
int i, j, count = 0;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == '*') {
count++;
}
}
}
return count;
}
void reveal_cell(char board[ROWS][COLS], int row, int col, int *remaining_cells) {
int i, j;
if (board[row][col] == '.') {
(*remaining_cells)--;
board[row][col] = '0' + count_adjacent_mines(board, row, col);
if (board[row][col] == '0') {
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS) {
reveal_cell(board, i, j, remaining_cells);
}
}
}
}
}
}
void play_game(char board[ROWS][COLS]) {
int row, col, remaining_cells = ROWS * COLS - MINES;
while (remaining_cells > 0) {
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
row--;
col--;
if (row >= 0 && row < ROWS && col >= 0 && col < COLS) {
if (board[row][col] == '*') {
printf("Game over!\n");
print_board(board, 1);
return;
} else {
reveal_cell(board, row, col, &remaining_cells);
print_board(board, 0);
}
}
}
printf("You won!\n");
}
```
这个程序使用了一个二维字符数组来表示扫雷的棋盘,其中每个字符表示该位置的状态,'.'表示未揭开,'*'表示地雷,'0'-'8'表示相邻地雷的数量。在程序开始时,使用`place_mines`函数随机放置地雷。然后使用`print_board`函数打印当前的棋盘。在玩家选择一个位置后,使用`reveal_cell`函数揭开该位置,如果该位置是地雷则游戏结束,否则更新棋盘并继续游戏,直到所有非地雷位置都被揭开。
阅读全文