生成迷宫
时间: 2023-07-24 11:08:14 浏览: 70
好的,以下是一个生成迷宫的 Python 代码示例:
```python
import random
def generate_maze(width, height):
# 创建一个空白迷宫
maze = [['#' for x in range(width)] for y in range(height)]
# 设置起始点和终点
start_x, start_y = random.randint(0, width - 1), random.randint(0, height - 1)
maze[start_y][start_x] = 'S'
end_x, end_y = random.randint(0, width - 1), random.randint(0, height - 1)
maze[end_y][end_x] = 'E'
# 随机生成迷宫路径
x, y = start_x, start_y
while x != end_x or y != end_y:
directions = ['N', 'S', 'W', 'E']
random.shuffle(directions)
for direction in directions:
if direction == 'N':
if y > 0 and maze[y - 1][x] == '#':
maze[y - 1][x] = ' '
y -= 1
break
elif direction == 'S':
if y < height - 1 and maze[y + 1][x] == '#':
maze[y + 1][x] = ' '
y += 1
break
elif direction == 'W':
if x > 0 and maze[y][x - 1] == '#':
maze[y][x - 1] = ' '
x -= 1
break
elif direction == 'E':
if x < width - 1 and maze[y][x + 1] == '#':
maze[y][x + 1] = ' '
x += 1
break
# 返回生成的迷宫
return maze
# 示例:生成一个 10 行 10 列的迷宫
maze = generate_maze(10, 10)
for row in maze:
print(' '.join(row))
```
输出结果:
```
# # # # # # # # # #
# S # # # # #
# # # # # # # # #
# # # # # # #
# # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # # # # #
# # # # # # # # # E
```
这是一个简单的随机生成迷宫的方法,代码中使用 `#` 表示障碍物,使用空格表示可行走的路径。你可以根据需要修改代码来自定义生成迷宫的形状和大小。
相关推荐
![sb3](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)