请帮我写一个扫雷的c语言代码
时间: 2024-05-06 11:21:12 浏览: 132
好的,以下是一个简单的扫雷c语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 10 // 行数
#define COL 10 // 列数
#define MINE_NUM 10 // 雷数
void initBoard(char board[][COL], int row, int col, char ch) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
board[i][j] = ch;
}
}
}
void printBoard(char board[][COL], int row, int col) {
printf(" ");
for (int i = 0; i < col; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 0; i < row; i++) {
printf("%d ", i);
for (int j = 0; j < col; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void setMine(char board[][COL], int row, int col, int mine_num) {
int count = 0;
while (count < mine_num) {
int i = rand() % row;
int j = rand() % col;
if (board[i][j] != '*') {
board[i][j] = '*';
count++;
}
}
}
void expand(char mine[][COL], char board[][COL], int row, int col, int x, int y) {
if (board[x][y] != '-') return;
int count = 0;
for (int i = x - 1; i <= x + 1; i++) {
if (i < 0 || i >= row) continue;
for (int j = y - 1; j <= y + 1; j++) {
if (j < 0 || j >= col) continue;
if (mine[i][j] == '*') count++;
}
}
if (count == 0) {
board[x][y] = ' ';
for (int i = x - 1; i <= x + 1; i++) {
if (i < 0 || i >= row) continue;
for (int j = y - 1; j <= y + 1; j++) {
if (j < 0 || j >= col) continue;
expand(mine, board, row, col, i, j);
}
}
} else {
board[x][y] = count + '0';
}
}
void play(char mine[][COL], char board[][COL], int row, int col) {
int remain = row * col - MINE_NUM;
while (remain > 0) {
int x, y;
printf("Please enter the coordinates of the mine (such as: 0 0): ");
scanf("%d %d", &x, &y);
if (x < 0 || x >= row || y < 0 || y >= col) {
printf("Illegal input, please re-enter.\n");
continue;
}
if (mine[x][y] == '*') {
printf("Boom! You lost!\n");
board[x][y] = '*';
break;
} else {
expand(mine, board, row, col, x, y);
printBoard(board, row, col);
remain--;
}
}
if (remain == 0) {
printf("Congratulations! You win!\n");
}
}
int main() {
char mine[ROW][COL];
char board[ROW][COL];
srand((unsigned int)time(NULL));
initBoard(board, ROW, COL, '-');
initBoard(mine, ROW, COL, '0');
setMine(mine, ROW, COL, MINE_NUM);
printBoard(board, ROW, COL);
play(mine, board, ROW, COL);
return 0;
}
```
这个扫雷游戏使用了一个二维数组来表示雷区和玩家可见的游戏面板,其中字符 '-' 表示未打开的格子,字符 '*' 表示有雷的格子,其它字符是数字,表示该格周围的雷数。玩家通过输入坐标,选择一个格子进行操作,首先判断该格是否是雷,是雷则结束游戏;否则根据该格周围的雷数展开该区域,直到游戏结束。
阅读全文