扫雷

扫雷

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_ROW 9
#define MAX_COL 9
#define MAX_MINE_COUNT 10

char mine_map[MAX_ROW][MAX_COL];//雷的位置
char show_map[MAX_ROW][MAX_COL];//每个位置周围有几颗雷

void Init()
{
	//1.先对show_map初始化,每个位置都设置为*
	for (int row = 0; row < MAX_ROW; row++)
	{
		for (int col = 0; col < MAX_COL; col++)
		{
			show_map[row][col] = '*';
		}
	}
	//2.再对mine_map初始化,把每个位置设置为'0',产生若干随机位置设置为'1'
	for (int row = 0; row < MAX_ROW; row++)
	{
		for (int col = 0; col < MAX_COL; col++)
		{
			mine_map[row][col] = '0';
		}
	}
	srand((unsigned int)time(0));
	int mine_count = 0;
	while (1)
	{
		//产生一组随机数
		int row = rand() % MAX_ROW;
		int col = rand() % MAX_COL;
		//非法判断
		if (mine_map[row][col]=='1')
		{
			continue;
		}
		mine_map[row][col] = '1';
		mine_count++;
		if (mine_count >= MAX_MINE_COUNT)
		{
			break;
		}
	}
}
//可以打印两种地图
void PrintMap(char the_map[MAX_ROW][MAX_COL])
{
	for (int row = 0; row < MAX_ROW; row++)
	{
		for (int col = 0; col < MAX_COL; col++)
		{
			printf("%c ",the_map[row][col]);
		}
		printf("\n");
	}
}
void UpdateShowMap(char mine_map[MAX_ROW][MAX_COL],char show_map[MAX_ROW][MAX_COL],
	int row,int col)
{
	//根据位置判断这个位置周围8个格子中雷的个数,把这个数字设置到show_map的对应位置上
	int count = 0;
	for (int r = row-1; r <= row+1; r++)
	{
		for (int c = col-1; c <= col+1; c++)
		{
			if (r == row && c == col)
			{
				continue;
			}
			if (r<0||r>=MAX_ROW||c<0||c>=MAX_COL)
			{
				continue;
			}
			if (mine_map[r][c] == '1')
			{
				count++;
			}
		}
	}
	//count设置到show_map中
	show_map[row][col] = '0' + count;
}
int  main()
{
	//1.初始化地图
	Init();
	int count = 0;
	while (1)
	{
		//2.打印地图show_map
		PrintMap(show_map);
		//printf("------------------------------\n");
		//PrintMap(mine_map);//为了测试,加上雷的地图
		//3.玩家输入坐标,翻开对应位置,需要校验合法性
		printf("请输入要翻开的位置(row,col):");
		int row = 0;
		int col = 0;
		scanf("%d %d",&row,&col);
		if (row<0||row>=MAX_ROW||col<0||col>=MAX_COL)
		{
			printf("输入有误,重新输入!");
			continue;
		}
		if (show_map[row][col]!='*')
		{
			printf("该位置已经翻开,重新输入");
			continue;
		}
		//4.判断是否踩雷了
		if (mine_map[row][col] == '1')
		{
			PrintMap(mine_map);
			printf("Game Over");
			break;
		}
		//5.判断游戏是否胜利,翻开所有的不是雷的格子之后即为胜利
		count++;//记录已经翻开了不是雷的格子个数
		if (count == MAX_COL * MAX_ROW - MAX_MINE_COUNT)
		{
			PrintMap(mine_map);
			printf("你赢了!\n");
			break;
		}
		//6.根据位置周围雷的情况,更新show_map
		UpdateShowMap(mine_map,show_map,row,col);
		//7.回去循环2
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值