用C语言写一个扫雷游戏
时间: 2023-04-05 09:00:53 浏览: 78
你好,我可以回答这个问题。以下是一个简单的扫雷游戏的 C 语言代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
void init_board(char board[ROWS][COLS], int rows, int cols, char ch);
void print_board(char board[ROWS][COLS], int rows, int cols);
void set_mines(char board[ROWS][COLS], int rows, int cols, int num_mines);
void set_numbers(char board[ROWS][COLS], int rows, int cols);
void play_game(char board[ROWS][COLS], char show_board[ROWS][COLS], int rows, int cols);
int main(void)
{
char board[ROWS][COLS];
char show_board[ROWS][COLS];
srand((unsigned int)time(NULL));
init_board(board, ROWS, COLS, '#');
init_board(show_board, ROWS, COLS, '*');
set_mines(board, ROWS, COLS, MINES);
set_numbers(board, ROWS, COLS);
print_board(show_board, ROWS, COLS);
play_game(board, show_board, ROWS, COLS);
return 0;
}
void init_board(char board[ROWS][COLS], int rows, int cols, char ch)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
board[i][j] = ch;
}
}
}
void print_board(char board[ROWS][COLS], int rows, int 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 rows, int cols, int num_mines)
{
int i, j, count = 0;
while (count < num_mines) {
i = rand() % rows;
j = rand() % cols;
if (board[i][j] != '*') {
board[i][j] = '*';
count++;
}
}
}
void set_numbers(char board[ROWS][COLS], int rows, int cols)
{
int i, j, count;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
if (board[i][j] != '*') {
count = 0;
if (i > 0 && j > 0 && board[i - 1][j - 1] == '*') count++;
if (i > 0 && board[i - 1][j] == '*') count++;
if (i > 0 && j < cols - 1 && board[i - 1][j + 1] == '*') count++;
if (j > 0 && board[i][j - 1] == '*') count++;
if (j < cols - 1 && board[i][j + 1] == '*') count++;
if (i < rows - 1 && j > 0 && board[i + 1][j - 1] == '*') count++;
if (i < rows - 1 && board[i + 1][j] == '*') count++;
if (i < rows - 1 && j < cols - 1 && board[i + 1][j + 1] == '*') count++;
board[i][j] = count + '0';
}
}
}
}
void play_game(char board[ROWS][COLS], char show_board[ROWS][COLS], int rows, int cols)
{
int i, j, x, y, count = 0, total = rows * cols - MINES;
char ch;
while (count < total) {
printf("请输入坐标(x,y)和操作(1:扫雷,2:标记):");
scanf("%d,%d,%c", &x, &y, &ch);
if (x < 0 || x >= rows || y < 0 || y >= cols) {
printf("坐标不合法,请重新输入!\n");
continue;
}
if (show_board[x][y] != '*') {
printf("该位置已经操作过,请重新输入!\n");
continue;
}
if (ch == '1') {
if (board[x][y] == '*') {
printf("你踩雷了,游戏结束!\n");
print_board(board, rows, cols);
return;
} else {
show_board[x][y] = board[x][y];
count++;
}
} else if (ch == '2') {
show_board[x][y] = 'F';
} else {
printf("操作不合法,请重新输入!\n");
continue;
}
print_board(show_board, rows, cols);
}
printf("恭喜你,扫雷成功!\n");
}
阅读全文