#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;
}
实践效果