小型项目——扫雷游戏(模块化实现)

完整代码

https://gitee.com/programmer-lego/c-language

视频,建议先看

扫雷游戏视频

打印菜单

void menu()
{
	printf("##############################################\n");
	printf("##################按1 玩游戏##################\n");
	printf("#################按0不玩游戏##################\n");
	printf("##############################################\n");
}

玩家做出选择

	do
	{
		printf("请做出选择->");
		scanf("%d", &n);
		switch (n)
		{
		case 1:
			game();
			break;
		case 0:
			printf("不玩游戏,退出程序\n");
			break;
		default:
			printf("选择错误,请从新输入");
			break;
		}
	} while (n);

创立雷盘,和展示给用户的雷盘

#define ROWS 11
#define COLS 11
#define ROW 9
#define COL 9
void game()
{
	char board[ROWS][COLS], show[ROWS][COLS];
	//初始化
}

初始化两个盘子

	init(board, ROWS, COLS, '0');
	init(show, ROWS, COLS, '*');
void init(char board[ROWS][COLS], int rows,int cols,char x)
{
	int a, b;
	for (a = 0; a < rows; a++)
	{
		for (b = 0; b < cols; b++)
		{
			board[a][b] = 'x';
		}
	}
}

打印盘子

void print(char board[ROWS][COLS], int row, int col)
{
	int a, b;
	for (b = 0; b <= col; b++)
	{
		printf("%d ", b);
	}
	printf("\n");
	for (a = 1; a <= row; a++)
	{
		printf("%d ", a);
		for (b = 1; b <=col; b++)
		{
			printf("%c ", board[a][b]);
		}
		printf("\n");
	}

}

小型项目——扫雷游戏(模块化实现)_第1张图片

放雷(电脑随机放雷)

void put(char board[ROWS][COLS], int row, int col)
{
	int sum = MINE;
	while (sum)
	{
		int x = rand() % row + 1;
		int y = rand() % col + 1;
		if (board[x][y] == '0')
		{
			board[x][y] = '1';
			sum--;
		}
	}
}

进行扫雷

int sweep_mine(char board[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int x, y;
	printf("请输入坐标->");
		scanf("%d%d", &x, &y);
		if (x > 0 && x <= row && y > 0 && y <= col)
		{
			s=judge(board, show, x, y);
		}
		else
		{
			printf("请输入正确的坐标->");
		}
		return s;
}
int judge(char board[ROWS][COLS], char show[ROWS][COLS], int x, int y)
{
	int a = 0, b = 0, sum = 0;
	if (x <= 0 || y <= 0 || x > 9 || y > 9||board[x][y]=='q')
	{
		return s;
	}
	else if (board[x][y] == '1')
	{
		return -1;
	}
	else
	{
		a = x - 1;
		b = y - 1;
		for (a=x-1; a <= x + 1; a++)
		{
			for (b=y-1; b <= y + 1; b++)
			{
				if (board[a][b] == '1')
				{
					sum++;
				}
			}
		}
		if (sum != 0)
		{
			show[x][y] = '0' + sum;
			s--;
		}
		else
		{
			show[x][y] = ' ';
			for (a = x - 1; a <= x + 1&&a<=ROW&&a>0; a++)
			{
				for (b=y-1; b <= y + 1&&b<=COL&&b>0; b++)
				{
					show[a][b] = ' ';
					s--;
					board[x][y] = 'q';
					judge(board, show, a, b);
				}
			}
		}
	}
}

判断是否成功

	while (s>0)
	{
		print(show, ROW, COL);
		s=sweep_mine(board, show, ROW, COL);//注意
		
	}
	if (s == 0)
	{
		printf("扫雷成功\n");
		//printf("下面是雷图\n");
		//print(board, ROW, COL);
	}
	else
	{
		printf("哈哈哈,你被炸死了\n");
		//printf("下面是雷图\n");
		//print(board, ROW, COL);
	}

小型项目——扫雷游戏(模块化实现)_第2张图片

你可能感兴趣的:(C语言,游戏,c语言,深度优先)