游戏实现——扫雷

相信大家都玩过扫雷吧,康康最近学习了如何用c语言代码实现该游戏,接下来就由康康向大家娓娓道来吧!

1.打印出游戏的菜单


void menu1()
{
	printf("*************************\n");
	printf("********1.play***********\n");
	printf("********0.exit***********\n");
	printf("*************************\n");

}



int main()
{
	int input = 0;
	
	srand((unsigned int)time(NULL));
	do
	{
		menu1();
		printf("请选择:\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			
			game();
			
			
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("输入错误请重新选择!\n");
			break;

		}
		
	} while (input);
}

​

2.创作游戏

void game()
{
	//创建棋盘
	char mineboard[ROWS][COLS] = { 0 };
	char showboard[ROWS][COLS] = { 0 };
	//棋盘初始化
	Initboard(mineboard, ROWS, COLS,'0');
	Initboard(showboard, ROWS, COLS, '*');
	//布雷
	Mysetting(mineboard, ROW, COL,Set);
	//打印棋盘
	/*Displayboard(mineboard, ROW, COL);*/
	Displayboard(showboard, ROW, COL);
	//辨雷
	Judgeboom(mineboard, showboard, ROW, COL);
	
}


void Initboard(char board[ROWS][COLS], int row, int col, char c)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = c;
		}
	}
}


void Displayboard(char board[ROWS][COLS], int row, int col)
{
	int i = 0;
	int j = 0;
	printf("--------扫雷--------\n");
	for (j = 0; j <= col; j++)
	{
		printf("%d ", j);
	}
	printf("\n");
	for (i = 1; i <= row; i++)
	{
		printf("%d ", i);
		for (j = 1; j <= col; j++)
		{
			
			printf("%c ", board[i][j]);

		}
		printf("\n");
	}

}


void Mysetting(char board[ROWS][COLS], int row, int col, int set)
{
	
	
	while(set)
	{
		int x = rand() % 8 + 1;
		int y = rand() % 8 + 1;
		if (board[x][y] != '1')
		{

			board[x][y] = '1';
			set--;
		}
			
		
	}
}
int Rrtmath(char board[ROWS][COLS],int x,int y)
{
	return board[x - 1][y] + board[x - 1][y - 1] + board[x][y - 1] + board[x + 1][y - 1] + board[x + 1][y]
		+ board[x + 1][y + 1] + board[x][y + 1] + board[x - 1][y + 1]
		- 8 * '0';

}
void Judgeboom(char mineboard[ROWS][COLS], char showboard[ROWS][COLS], int row, int col)
{
	int x = 0;
	int y = 0;
	int count = ROW * COL - Set;
	while(count)
	{
		printf("请输入坐标:\n");
		scanf("%d%d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (showboard[x][y] != '*')
			{
				printf("该坐标排查过了不能重复排查请重新选择!\n");
			}
			else
			{
				//如果是雷
				if (mineboard[x][y] == '1')
				{
					printf("很抱歉,你被炸死了\n");
					Displayboard(mineboard, ROW, COL);
					break;
				}
				//如果不是雷
				else
				{
					int ret = Rrtmath(mineboard, x, y);
					showboard[x][y] = ret + '0';
					Displayboard(showboard, ROW, COL);
					count--;
				}
			}
			
		}
		else
			printf("输入错误请重新输入!\n");
	}
	if (count == 0)
	{
		printf("恭喜你获得游戏的胜利!!");
		Displayboard(mineboard, ROW, COL);
	}
}

逻辑很简单,大家可以简单的借鉴一下,毕竟是初学者多多支持!

你可能感兴趣的:(游戏)