用c语言给我写一个扫雷小游戏
时间: 2024-01-26 22:02:58 浏览: 153
好的,以下是一个简单的扫雷小游戏的C语言代码,你可以在终端或命令行中运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 9
#define COLS 9
#define MINE_NUM 10
void init_board(char board[ROWS][COLS], char ch);
void display_board(char board[ROWS][COLS]);
void set_mines(char board[ROWS][COLS]);
int get_mine_count(char board[ROWS][COLS], int row, int col);
void expand_board(char board[ROWS][COLS], int row, int col);
void play_game(char board[ROWS][COLS]);
int main() {
char board[ROWS][COLS];
init_board(board, '*');
set_mines(board);
play_game(board);
return 0;
}
void init_board(char board[ROWS][COLS], char ch) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = ch;
}
}
}
void display_board(char board[ROWS][COLS]) {
int i, j;
printf(" ");
for (i = 0; i < COLS; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%d ", i);
for (j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void set_mines(char board[ROWS][COLS]) {
int i, j, count = 0;
srand(time(NULL));
while (count < MINE_NUM) {
i = rand() % ROWS;
j = rand() % COLS;
if (board[i][j] != 'M') {
board[i][j] = 'M';
count++;
}
}
}
int get_mine_count(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] == 'M') {
count++;
}
}
}
return count;
}
void expand_board(char board[ROWS][COLS], int row, int col) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS || board[row][col] != '*') {
return;
}
int count = get_mine_count(board, row, col);
board[row][col] = count + '0';
if (count == 0) {
expand_board(board, row - 1, col - 1);
expand_board(board, row - 1, col);
expand_board(board, row - 1, col + 1);
expand_board(board, row, col - 1);
expand_board(board, row, col + 1);
expand_board(board, row + 1, col - 1);
expand_board(board, row + 1, col);
expand_board(board, row + 1, col + 1);
}
}
void play_game(char board[ROWS][COLS]) {
int row, col, count = 0;
while (1) {
display_board(board);
printf("Enter row and column number (separated by a space): ");
scanf("%d %d", &row, &col);
if (board[row][col] == 'M') {
printf("Game over!\n");
display_board(board);
return;
}
expand_board(board, row, col);
count++;
if (count == ROWS * COLS - MINE_NUM) {
printf("You win!\n");
display_board(board);
return;
}
}
}
```
这个程序定义了一个9x9的扫雷游戏棋盘,其中包含10个地雷。游戏开始时,所有方格都是未知的,用'*'表示。玩家可以选择一个方格进行扫描,如果方格中没有地雷,则该方格将被展开,显示相邻方格中的地雷数。如果方格中有地雷,则游戏结束。如果玩家成功地展开了所有非地雷方格,则游戏胜利。
你可以在终端或命令行中运行此程序,按照提示输入行和列号来选择扫描的方格。
阅读全文