海龟迷宫python
时间: 2024-01-20 22:16:36 浏览: 87
python实现海龟绘图程序
以下是一个使用Python的Turtle库绘制海龟迷宫的例子:
```python
import turtle
# 创建迷宫地图
maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
# 设置海龟的初始位置和方向
start_x = -180
start_y = 180
turtle.penup()
turtle.goto(start_x, start_y)
turtle.pendown()
turtle.setheading(0)
# 定义绘制迷宫的函数
def draw_maze():
for i in range(len(maze)):
for j in range(len(maze[i])):
if maze[i][j] == 1:
turtle.fillcolor("black")
else:
turtle.fillcolor("white")
turtle.begin_fill()
for _ in range(4):
turtle.forward(40)
turtle.right(90)
turtle.end_fill()
turtle.penup()
turtle.forward(40)
turtle.pendown()
turtle.penup()
turtle.goto(start_x, start_y - (i + 1) * 40)
turtle.pendown()
# 调用绘制迷宫的函数
draw_maze()
# 定义探索迷宫的函数
def explore_maze(x, y):
if maze[x][y] == 0:
maze[x][y] = 2
turtle.fillcolor("yellow")
turtle.begin_fill()
for _ in range(4):
turtle.forward(40)
turtle.right(90)
turtle.end_fill()
turtle.penup()
turtle.goto(start_x + y * 40, start_y - x * 40)
turtle.pendown()
if x == 9 and y == 9:
turtle.write("Exit", align="center", font=("Arial", 16, "bold"))
else:
if x < 9 and maze[x + 1][y] == 0:
explore_maze(x + 1, y) # 向南移动
if x > 0 and maze[x - 1][y] == 0:
explore_maze(x - 1, y) # 向北移动
if y < 9 and maze[x][y + 1] == 0:
explore_maze(x, y + 1) # 向东移动
if y > 0 and maze[x][y - 1] == 0:
explore_maze(x, y - 1) # 向西移动
# 调用探索迷宫的函数,从起点开始探索
explore_maze(1, 1)
turtle.done()
```
这段代码使用Turtle库绘制了一个迷宫地图,并通过递归调用探索迷宫的函数来寻找出口。海龟从起点开始,向北、南、西、东四个方向移动,直到找到出口为止。在探索过程中,海龟经过的位置会被标记为黄色。
阅读全文