数组1 放置好的雷 信息 char mine[11][11]
数组3 排除出的雷的信息(用户界面) char show[11][11] //11是因为需要搜素边缘区域附近的雷有几个时,方便搜素,向外扩大一格。
展示数组初始化 ' * ' 雷数组初始化 0
test.c
#define _CRT_SECURE_NO_WARNINGS #include#include "game.h" void menu() { //菜单显示 printf("*********************************n"); printf("********1.开始 2.退出***********n"); printf("*********************************n"); } void game() { //开始游戏 char mine[ROWS][COLS] = { 0 };//雷数组 char show[ROWS][COLS] = { 0 };//展现数组 //初始化数组为指定内容 //mine在没有布置雷都是'0' InitBoard(mine, ROWS, COLS, '0'); //show在没有布置雷都是'*' InitBoard(show, ROWS, COLS, '*'); DisplayBoard(mine, ROW, COL); //DisplayBoard(show,ROW,COL); //放置雷 SetMine(mine, ROW, COL); //排查雷 FindMine(mine, show, ROW, COL); } int main() { srand((unsigned int)time(NULL));//产生随机数种子 int input = 0; do { menu();//显示菜单 printf("请选择>:");//选择游戏 scanf("%d", &input); switch (input) { case 1: game();//选择1,进入游戏 break; case 0: printf("退出游戏!n");//选择0,退出游戏 default: printf("选择错误!n");//选择其他,重新输入 break; } } while (input); return 0; }
game.h
#include#include #include #define ROW 9//行数 #define COL 9//列数 #define ROWS ROW+2 #define COLS COL+2 #define MINE_COUNT 10//雷数 void InitBoard(char board[ROWS][COLS], int rows, int cols, char ch); void DisplayBoard(char board[ROWS][COLS],int row, int col); void SetMine(char board[ROWS][COLS], int row, int col); void FindMine(char mine[ROWS][COLS],char show[ROWS][COLS], int row, int col);
game.c
#define _CRT_SECURE_NO_WARNINGS #include "game.h" void InitBoard(char board[ROWS][COLS], int rows, int cols, char ch) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i][j] = ch; } } } void DisplayBoard(char board[ROWS][COLS], int row, int col) { //打印行列 printf("----------------扫雷游戏-------------------n"); for (int j = 0; j <= col; j++) { printf("%d ", j); } printf("n"); for (int i = 1; i <= row; i++) { printf("%d ", i); for (int j = 1; j <= col; j++) { printf("%c ", board[i][j]); } printf("n"); } } void SetMine(char board[ROWS][COLS], int row, int col) { // 埋雷 int count = MINE_COUNT; while(count) { int x = rand() % row + 1; int y = rand() % col + 1; if (board[x][y] == '0') { board[x][y] = '1'; count--; } } } int get_mine_count(char board[ROWS][COLS], int x, int y) { //计算该雷周围雷的个数 return board[x - 1][y] + board[x - 1][y - 1] + board[x - 1][y + 1] + board[x][y - 1] + board[x][y + 1] + board[x + 1][y - 1] + board[x + 1][y] + board[x + 1][y + 1]; } void FindMine(char mine[ROWS][COLS],char show[ROWS][COLS], int row, int col) { //排雷 int x = 0; int y = 0; static int win = 0; while (win < (COL * ROW - MINE_COUNT))//如果排雷的个数小于所有总数-雷的个数则循环 { printf("请输入排查坐标n"); scanf("%d %d", &x, &y); if (x>= 1&&x<=row,y >= 1 && y<=col) { if (mine[x][y] == '1')//踩到雷 { printf("你死了n"); DisplayBoard(mine, ROW, COL); break; } else { win++; int count = get_mine_count(mine, x, y); //统计mine数组中周围雷的个数 show[x][y] = count + '0';//转化成数字字符 DisplayBoard(show, ROW, COL); } } else { printf("非法输入,重新输入:n"); } } if (win == row*col - MINE_COUNT) { printf("赢啦!n"); DisplayBoard(mine, ROW, COL); } }



