此代码功能随机生成任意难度迷宫:) 所有迷宫原理八九不离十
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define NUMBER 50
#define RANK 80
char arr[NUMBER][NUMBER];
int fx[4] = { -1,1,0,0 };
int fy[4] = { 0,0,-1,1 };
/*起始坐标*/
int firstx = 0;
int firsty = 0;
/*终点坐标*/
int lastx = 0;
int lasty = 0;
void showmap();
bool makemap(int x, int y);//制作地图
bool unerror(int x, int y);//移除四角
bool wherewego(int x,int y);//路径
bool iswork(int x,int y); //走的判断
int main() {
//初始化数组
for (int i = 0; i < NUMBER - 1; i++)
{
for (int j = 0; j < NUMBER - 1; j++)
{
arr[i][j] = '#';
}
}
srand(time(NULL));
int x = 0;
int y = 0;
//获取起始坐标
do
{
x = 0 + rand() % (NUMBER - 1);
y = 0 + rand() % (NUMBER - 1);
while (x != 0 && y != 0 && y != NUMBER - 2 && x != NUMBER - 2)
{
x = 0 + rand() % (NUMBER - 1);
y = 0 + rand() % (NUMBER - 1);
}
} while (unerror(x, y) == false);//等于四角就重来
arr[x][y] = '.';
firstx = x;
firsty = y;
printf("迷宫起始坐标:(%d,%d)\n", x, y);
/*迷宫函数调用*/
makemap(x, y);
/*随机获取迷宫终点坐标*/
int counter = 0;
do
{
lastx = 0 + rand() % (NUMBER - 1);
lasty = 0 + rand() % (NUMBER - 1);
while (lastx != 0 && lasty != 0 && lasty != NUMBER - 2 && lastx != NUMBER - 2)
{
lastx = 0 + rand() % (NUMBER - 1);
lasty = 0 + rand() % (NUMBER - 1);
}
++counter;
} while (unerror(lastx, lasty) == false && counter < NUMBER * 4);
if (counter < NUMBER * 4)
{
arr[lastx][lasty] = '.';
printf("迷宫终点坐标:(%d,%d)\n", lastx, lasty);
}
else
{
printf("生成失败!\n");
}
//起点打印个X作为标记
arr[firstx][firsty] = 'X';
/*走迷宫*/
makemap(firstx, firsty);
/*打印迷宫*/
showmap();
system("pause");
return 0;
}
//判断越界问题
bool iswork( int x, int y)
{
if (arr[x][y] != '#' && arr[x][y] != 'X' && x > 0 && y > 0 && x < NUMBER && y < NUMBER)
{
return true;
}
return false;
}
bool wherewego(int x, int y)
{
int count = 0;
for (int i = 0; i < 4; i++)
{
int nextx = x + fx[i];
int nexty = y + fy[i];
if (arr[nextx][nexty] == '#')
{
count++;
if (count >= 3)
{
return true;
}
}
}
return false;
}
bool makemap(int x, int y)
{
bool wherewego(int x, int y);//选择路径
for (int j = 0; j < RANK; j++)
{
int i = rand() % 4;
int nextx = x + fx[i];
int nexty = y + fy[i];
if (arr[nextx][nexty] == '#' && nextx >= 0 && nextx < NUMBER - 1 && nexty < NUMBER - 1 && nexty >= 0)
{
if (wherewego(nextx, nexty) == true)
{
arr[nextx][nexty] = '.';
if (makemap(nextx, nexty) == true) return true;
}
}
}
return false;
}
//排除四个角
bool unerror(int x, int y) {
if ((x == 0 && y == 0) || (x == 0 && y == 11) || (x == 11 && y == 0) || (x == 11 && y == 11)) {
return false;
}
return true;
}
void showmap()
{
for (int i = 0; i < NUMBER; i++)
{
for (int j = 0; j < NUMBER; j++)
{
printf("%2c", arr[i][j]);
}
printf("\n");
}
}