import random
# 生成迷宫
def gen_maze():
maze = []
data = []
for _ in range(10):
for i in range(11):
if len(data) == 10:
maze.append(data)
data = []
data.append(random.randint(0, 1))
# for i in maze:
# print(i)
return maze
# 生成墙
def gen_wall(maze):
maze[0] = [0 for _ in maze[0]]
maze[-1] = [0 for _ in maze[-1]]
for i in maze:
i[0] = 0
i[-1] = 0
return maze
# 初始化迷宫
def ini_maze(maze):
maze[1] = [0 for _ in maze[1]]
maze[-2] = [0 for _ in maze[-2]]
# 入口随机
start = random.randint(1, 8)
maze[1][start] = 1
# 出口随机
end = random.randint(1, 8)
maze[-2][end] = 1
return maze, (1, start), (8, end)
# 随机生成路径(单层随机生成)
def random_path(maze, start_position, end_position):
start_point = (start_position[0], start_position[1])
end_point = (end_position[0], end_position[1])
start_row = start_point[0] + 1
start_col = start_point[1]
# print(start_row, start_col)
if maze[start_row][start_col] != 1:
maze[start_row][start_col] = 1
while True:
if start_row == 7:
break
# 是否左右移动
move = ["L", "R", "D"]
is_move = move[random.randint(0, len(move) - 1)]
if is_move == "L" and start_col != 1:
maze[start_row][start_col] = 1
start_col -= 1
maze[start_row][start_col] = 1
continue
if is_move == "R" and start_col != 8:
maze[start_row][start_col] = 1
start_col += 1
maze[start_row][start_col] = 1
continue
if is_move == "D" and start_row != 7:
maze[start_row][start_col] = 1
start_row += 1
maze[start_row][start_col] = 1
continue
# print(start_row, start_col)
if start_col < end_point[1]:
for j in range(start_col, end_point[1]):
maze[8][j] = 1
else:
for j in range(end_point[1], start_col):
maze[8][j] = 1
return maze
def pass_maze(maze,start,end):
lst = [start]
while lst:
now = lst[-1]
row, col = now
maze[row][col] = 2
if now == end:
print("出来了")
print(lst)
break
if maze[row - 1][col] == 1:
lst.append((row - 1, col))
continue
elif maze[row][col + 1] == 1:
lst.append((row, col + 1))
continue
elif maze[row + 1][col] == 1:
lst.append((row + 1, col))
continue
elif maze[row][col - 1] == 1:
lst.append((row, col - 1))
continue
else:
lst.pop()
print("-" * 100)
print("走出迷宫的路径")
for i in maze:
print(i)
wall = gen_maze()
res = gen_wall(wall)
ini_maze, start, end = ini_maze(res)
# for i in ini_maze:
# print(i)
print("入口以及出口位置")
print(start, end)
print("*" * 100)
print("生成的迷宫")
maze = random_path(ini_maze, start, end)
for i in maze:
print(i)
pass_maze(maze,start,end)
最近对迷宫算法很是着迷,随便找了个视频学习了一下,以上是迷宫生成的思路,和走出迷宫的方法,欢迎大家指正。