扫雷

小项目—扫雷

#include 
#include 
#include 
#include 
/*第一次尝试做小游戏hhh*/

using namespace std;

const int row = 10;      //地图的行数
const int col  = 10;       //地图的列数
const int num = 10;    //地雷数

char map[12][12];  //加二是多了个辅助区,防止越界
char g[12][12];
int cnt;

void gameinit();  //初始化地图
void gameprint(); //打印地图
int playgame();     //开始玩游戏
void displayboard(int a,int b); //展示扫出来的棋盘
//int  count(int cnt); //统计个数,如果雷排完了,就结束

int main() 
{
	gameinit();
	gameprint();
	while (1)
	{
		if (playgame() == '#')
			break;
		else
		{
			cnt++;
			if (cnt == row * col - num)
			{
				printf("恭喜你!成功排完所有雷!\n");
				return 0;
			}
		}
	}
	printf("笨蛋,你踩到雷了!!!\n");
	return 0;
}

void gameinit()
{
	//游戏区和辅助区全部初始化为0
	for (int i = 0; i < row + 2; i++)
	{
		for (int j = 0; j < col + 2; j++)
		{
			map[i][j] = '0';
		}
	}

	for (int i = 1; i <= row; i++)
	{
		for (int j = 1; j <= col; j++)
			g[i][j] = '*';
	}

	srand((unsigned int)time(NULL));    

	for (int i = 1; i <= row; )
	{
			int r,c;                                                     //设计随机地雷
			r = rand() % row + 1;
			c = rand() % col + 1;
			if (map[r][c] == '0')
			{
				map[r][c] = '#';
				i++;
			}
	}

	for (int i = 1; i <= row; i++)
	{
		for (int j = 1; j <= col; j++)
		{
			if (map[i][j] != '#')
			{
				for (int k = i - 1; k <= i + 1; k++)
				{
					for (int l = j - 1; l <= j + 1; l++)
					{
						if (map[k][l] == '#')
							map[i][j] = map[i][j] + 1;
					}
				}
			}
		}
	}

}

void gameprint()
{
	for (int i = 1; i <= row; i++)
	{
		for (int j = 1; j <= col; j++)
		{
			printf("%c ",g[i][j]);
		}
		printf("\n");
	}
}

int playgame()
{
	printf("请选择行和列:\n");
	int x, y;
	while (1)
	{
		cin >> x >> y;
		if (x < 1 || x>10 || y < 1 || y>10)
		{
			printf("输入错误,请重新输入!\n");
		}
		else
			break;
	}
	system("cls");
	displayboard(x, y);
	return map[x][y];
}

void displayboard(int a,int b)
{
	g[a][b] = map[a][b];
	for (int i = 1; i <= row; i++)
	{
		for (int j = 1; j <= col; j++)
			printf("%c ", g[i][j]);
		printf("\n");
	}
	
}

你可能感兴趣的:(扫雷)