递归回溯法绘制迷宫 easyx库

该博客介绍了如何利用C++编程,结合EasyX图形库和随机数生成器创建一个64x64的二维迷宫。通过设定不同方向的移动规则,不断绘制并删除墙壁,最终生成一条从起点到终点的路径。文章通过具体代码展示了实现过程,包括初始化迷宫、判断是否有通路、随机选择方向和绘制墙等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <easyx.h>
#include <time.h>
int direction = 0;//0表示向右, 1表示向下,2表示向上,3表示向左
int n = 64 * 64 - 1;
struct Space
{
	int x;
	int y;
	Space* bef = NULL;
	bool att;//0表示未访问,1表示已访问
};
Space space[64][64];
int x = 1;
int y = 1;
int z = 1;
bool ifHaveWay()
{
	if (space[x - 1][y].att && space[x + 1][y].att && space[x][y - 1].att && space[x][y + 1].att)
		return 0;
	else
		return 1;
}
void RandDirection()
{
	while (1)//获取方向
	{
		direction = rand() % 4;
		if (direction == 3 && space[x - 1][y].att)
			continue;
		if (direction == 0 && space[x + 1][y].att)
			continue;
		if (direction == 2 && space[x][y - 1].att)
			continue;
		if (direction == 1 && space[x][y + 1].att)
			continue;
		break;
	}
}
void WallBreak()
{
	setlinecolor(BLACK);
	if (direction == 1)
		line(x * 10 + 1, y * 10, x * 10 + 9, y * 10);
	if (direction == 0)
		line(x * 10, y * 10 + 1, x * 10, y * 10 + 9);
	if (direction == 3)
		line(x * 10 + 10, y * 10 + 1, x * 10 + 10, y * 10 + 9);
	if (direction == 2)
		line(x * 10 + 1, y * 10 + 10, x * 10 + 9, y * 10 + 10);
}
void FoundWay()
{
	int tx, ty;
	Space* p1 = NULL;
	while (x != 1 || y != 1 || z)
	{
		while (ifHaveWay())//画迷宫主线
		{
			p1 = &space[x][y];
			space[x][y].att = 1;
			RandDirection();
			if (direction == 0)
				x++;
			if (direction == 1)
				y++;
			if (direction == 2)
				y--;
			if (direction == 3)
				x--;
			WallBreak();
			space[x][y].bef = p1;
			//Sleep(5);
		}
		space[x][y].att = 1;
		tx = x;
		ty = y;
		x = space[tx][ty].bef->x;
		y = space[tx][ty].bef->y;
		z = 0;
	}
}
//初始化
void SetGraph()
{
	for (int i = 0; i < 64; i++)
	{
		for (int j = 0; j < 64; j++)
		{
			space[i][j].x = i;
			space[i][j].y = j;
		}
	}
	//将迷宫内元素清零
	for (int i = 0; i < 64; i++)
	{
		for (int j = 0; j < 64; j++)
		{
			space[i][j].att = 0;
		}
	}
	//将迷宫的周围建墙(设置为已访问)
	for (int i = 0; i < 64; i++)
	{
		space[0][i].att = 1;
		space[63][i].att = 1;
		space[i][0].att = 1;
		space[i][63].att = 1;
	}
	initgraph(640, 640);
}
void DrawWall()
{
	for (int i = 0; i < 640; i += 10)
	{
		line(i, 0, i, 640);
	}
	for (int i = 0; i < 640; i += 10)
	{
		line(0, i, 640, i);
	}
	solidrectangle(0, 0, 640, 10);
	solidrectangle(0, 0, 10, 640);
	solidrectangle(630, 0, 640, 640);
	solidrectangle(0, 630, 640, 640);
}
int main()
{
	srand(time(NULL));
	SetGraph();
	DrawWall();
	FoundWay();
	setlinecolor(WHITE);
	system("pause");
	return 0;
}

实践效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值