u012912259 于 2013.12.17 16:42 提问

C语言简单生成并控制迷宫

#include
#include
#include

void PrintTheMaze();
void SetMaze(int maze[][40], int row, int col, int size);
void control();

int maze[40][40]; //定义一个二维数组
int size;
int i,j;

//**************************主函数*******************************
main()
{
srand((unsigned)time(NULL));
int maze[40][40] = {0};
printf("size of d maze[N^2]: ");
scanf("%d",&size);
SetMaze(maze,rand() % (size - 2) + 1, rand() % (size - 2) + 1, size);
PrintTheMaze(size);
//control();
}

//***************************创建迷宫***************************
void SetMaze(int maze[][40], int row, int col, int size)
{
int t, n;
int drc[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//控制遍历顺序
//srand((unsigned)time(NULL));

for(j = 0; j < 4; j++)//打乱遍历顺序
{
n = rand() % 4;
t = drc[i][0]; drc[i][0] = drc[n][0]; drc[n][0] = t;

t = drc[i][1]; drc[i][1] = drc[n][1]; drc[n][1] = t;
}
if (row > 0 && row < size - 1 && col < size - 1 && col > 0) //限定遍历范围
{
maze[row][col] = 1; //随机定义通路
for(i = 0; i < 4; i++) //扫描旁边任意一格

{
if (maze[row + 2 * drc[i][0]][col + 2 * drc[i][1]] == 0) //如果旁边是墙
{
maze[row + drc[i][0]][col + drc[i][1]] = 1; //把中间变成路
SetMaze(maze, row + 2 * drc[i][0], col + 2 * drc[i][1], size);
}
}
}

``````for(i = 0 ; i <size ; i++)          // 把四周设置为边墙
{
maze[0][i] = 0;
maze[size - 1][i] = 0;
maze[i][0] = 0;
maze[i][size - 1] = 0;
}
maze[0][1] = 1;//设置入口
maze[size - 1][size - 2] = 1;//设置出口
``````

}

//**************************输出迷宫************************************
void PrintTheMaze(int size)
{
//SetMaze(maze,rand() % (size - 2) + 1, rand() % (size - 2) + 1, size);
//int i,j;
for (i = 0; i < size; ++i)
{
for (j = 0; j < size; ++j)
{
if (maze[i][j] == 0)
printf("■");
else
if (maze[i][j] == 1)
printf(" ");
else
printf("囧");

}
printf("\n");
}
//control();
}

//*****************************控制迷宫*************************************
void control()
{
char e;
int x,y,k;
x=0, y=1;
maze[x][y]=3;
for (;;)
{
system("cls");
PrintTheMaze(size);
e=getch();
switch (e)
{
case 'a': //向左走判断
{
if (maze[y][x-1]==1)
{
maze[y][x]=1; maze[y][x-1]=2; x--;
}
}
break;

case 's': //向下走判断
{
if (maze[y+1][x]==1)
{
maze[y][x]=1; maze[y+1][x]=2; y++;
}
}
break;

case 'd': //向右走判断
{
if (maze[y][x+1]==1)
{
maze[y][x]=1; maze[y][x+1]=2; x++;
}
}
break;

case 'w': //向上走判断
{
if (maze[y-1][x]==1)
{
maze[y][x]=1; maze[y-1][x]=2; y--;
}
}
break;
case 'q': return;
}
}
}