扫雷游戏
test.c — 与游戏相关的逻辑测试
game.c — 与游戏相关的函数实现
game.h — 与游戏相关的函数的声明
//test.c#define _CRT_SECURE_NO_WARNINGS 1#include "game.h"void menu(){printf("******************************\n");printf("**********1.play**************\n");printf("**********0.exit**************\n");printf("******************************\n");}void game(){char mine[ROWS][COLS] = { 0 }; //存放部署好的雷的信息char show[ROWS][COLS] = { 0 }; //存放排查出的雷的信息InitBoard(mine, ROWS, COLS, '0'); //雷盘初始化DisplayBoard(mine, ROW, COL); //打印雷盘InitBoard(show, ROWS, COLS, '*');DisplayBoard(show, ROW, COL);Set_Mine(mine, ROW, COL); //部署雷DisplayBoard(mine, ROW, COL);Find_Mine(mine, show, ROW, COL); //排查雷}int main(){int input = 0;srand((unsigned int)time(NULL));do{menu(); //游戏菜单printf("请选择:");scanf("%d", &input);switch (input){case 1:game(); //扫雷游戏break;case 0:printf("退出游戏\n");break;default:printf("输入错误,重新输入!\n");}} while (input);}
//game.c
#define _CRT_SECURE_NO_WARNINGS 1#include "game.h"void InitBoard(char board[ROW][COL], int rows, int cols, char set)
{int i = 0;int j = 0;for (i = 0;i < rows;i++){for (j = 0;j < cols;j++){board[i][j] = set;}}
}void DisplayBoard(char board[ROW][COL], int row, int col)
{int x = 0;int y = 0;printf("------ 扫雷游戏 -------\n");for (x = 0;x <= row;x++){printf("%d ", x);}printf("\n");for (x = 1;x <= row;x++){printf("%d ", x);for (y = 1;y <= col;y++){printf("%c ",board[x][y]);}printf("\n");}printf("------ 扫雷游戏 -------\n");
}
static int get_mine_count(char mine[ROW][COL], int x, int y)
{return mine[x-1][y] +mine[x-1][y-1] +mine[x][y-1] +mine[x+1][y-1] +mine[x+1][y] +mine[x+1][y+1] +mine[x][y+1] +mine[x-1][y-1] - 8 * '0';
}void Set_Mine(char mine[ROWS][COLS], int row, int col)
{int count = 10;while (count){int x = rand() % row + 1;int y = rand() % col + 1;if (mine[x][y] == '0'){mine[x][y] = '1';count--;}}
}void Find_Mine(char mine[ROW][COL], char show[ROW][COL], int row, int col)
{int x = 0;int y = 0;int win = 0;while (win < row * col - Count){printf("请输入选择的坐标:");scanf("%d %d", &x, &y);if (x >= 1 && x <= row && y >= 1 && y <= col) //判断坐标的合理性{if (mine[x][y] == '1'){printf("失败");break;}else{int count = get_mine_count(mine, x, y); //不是雷的前提下,计算x,y坐标中周围有多少个雷show[x][y] = count + '0';DisplayBoard(show, ROW, COL); //打印排查出的信息win++;}}else{printf("错误,重新输入\n");}}if (win = row * col - Count){printf("恭喜获胜\n");}
}
//game.h
#pragma once#include <stdio.h>
#include <stdlib.h>
#include <time.h>#define ROW 9
#define COL 9#define ROWS ROW+2
#define COLS COL+2#define Count 10//初始化函数声明
void InitBoard(char board[ROW][COL], int rows, int cols, char set);//打印函数声明
void DisplayBoard(char board[ROW][COL], int row, int col);//部署函数声明
void Set_Mine(char mine[ROWS][COLS], int row, int col);//排查函数声明
void Find_Mine(char mine[ROW][COL], char show[ROW][