在test.cpp中测试
#include"game.h"
void menu()
{
//打印初始界面
cout << "******************" << endl;
cout << "******************" << endl;
cout << "****1.开始游戏*****" << endl;
cout << "****0.结束游戏*****" << endl;
cout << "******************" << endl;
cout << "******************" << endl;
}
void game()
{
//实现扫雷游戏
//mine中存放雷
char mine[ROWS][COLS] = { '0' };//数组全部初始化为0
//show中存放排查出的雷的信息
char show[ROWS][COLS] = { '*' };//数组全部初始化为*
//初始化棋盘
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
//打印棋盘
//DisplayBoard(mine, ROW, COL);
//DisplayBoard(show, ROW, COL);
//布置雷
SetMine(mine,ROW,COL);
//DisplayBoard(mine, ROW, COL);
DisplayBoard(show, ROW, COL);
//排查雷
FindMine(mine ,show,ROW,COL);
}
void test()
{
int input;
srand((unsigned int)time(NULL));
do
{
menu();
cout << "请选择->" << endl;
cin >> input;
switch (input)
{
case 1:
cout << "开始扫雷" << endl;
game();
break;
case 0:
cout << "退出游戏" << endl;
break;
default :
cout << "选择错误,请重新选择" << endl;
}
} while (input);
}
int main()
{
test();
return 0;
}
在game.cpp中实现扫雷主要功能
#include"game.h"
#include<ctime>
#include<cstdlib>
//初始化棋盘
void InitBoard(char arr[ROWS][COLS], int rows, int cols,char temp)
{
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
arr[i][j] = temp;
}
}
}
//打印棋盘
void DisplayBoard(char arr[ROWS][COLS], int row, int col)
{
int i;
//打印列号
cout << "----------扫雷----------" << endl;
for (i = 0; i <= COL; i++) {
cout << i;
}
cout << endl;
for (i = 1; i <= ROW; i++) {
cout << i;
for (int j = 1; j <= COL; j++) {
cout << arr[i][j];
}
cout << endl;
}
}
//布置雷
void SetMine(char mine[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if(mine[x][y] == '0') {
mine[x][y] = '1';
count--;
}
}
}
//计算周围雷的个数
static int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
return mine[x + 1][y] +
mine[x - 1][y] +
mine[x + 1][y + 1] +
mine[x][y + 1] +
mine[x - 1][y + 1] +
mine[x + 1][y - 1] +
mine[x][y - 1] +
mine[x - 1][y - 1] - 8 * '0';
}
//找雷
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x;
int y;
while(1)
{
cout << "请输入要排查的雷" << endl;
cin >> x >> y;
//判断数据是否有效
if (x >= 1 && x <= row && y >= 1 && y <= col) {
if (mine[x][y] == '1') {
cout << "很遗憾你被炸死了"<<endl;
DisplayBoard(mine, ROW, COL);
break;
}
else {
//该坐标不是雷,显示周围有几个雷
int count=GetMineCount(mine,x,y);
show[x][y] = count + '0';
DisplayBoard(show, ROW, COL);
}
}
else
{
cout << "输入无效,请重新输入";
}
}
}
在game.h中声明行列,雷的个数,函数
#pragma once
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
//控制行和列
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define EASY_COUNT 10
//声明函数
void test();
void InitBoard(char arr[ROWS][COLS], int rows ,int cols,char set);
void DisplayBoard(char arr[ROWS][COLS], int row, int col);
void SetMine(char arr[ROWS][COLS],int row,int col);
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
评论 (0)