python画汉诺塔
时间: 2023-11-15 16:59:14 浏览: 91
Python可以使用turtle库来画汉诺塔。下面是一个简单的示例代码:
```python
import turtle
# 定义汉诺塔函数
def hanoi(n, a, b, c):
if n > 0:
hanoi(n-1, a, c, b)
b.append(a.pop())
draw_tower(tower_a, tower_b, tower_c)
hanoi(n-1, c, b, a)
# 定义画塔函数
def draw_tower(tower_a, tower_b, tower_c):
turtle.clear()
turtle.penup()
turtle.goto(-200, -100)
turtle.pendown()
turtle.goto(200, -100)
turtle.goto(200, 100)
turtle.goto(-200, 100)
turtle.goto(-200, -100)
turtle.penup()
turtle.goto(-150, -80)
turtle.pendown()
turtle.goto(150, -80)
turtle.goto(150, 80)
turtle.goto(-150, 80)
turtle.goto(-150, -80)
turtle.penup()
draw_disk(tower_a, -150, -60)
draw_disk(tower_b, 0, -60)
draw_disk(tower_c, 150, -60)
turtle.update()
# 定义画盘子函数
def draw_disk(tower, x, y):
for i in range(len(tower)):
turtle.goto(x, y + i * 20)
turtle.pendown()
turtle.goto(x + tower[i] * 6, y + i * 20)
turtle.penup()
# 初始化三个塔
tower_a = [6, 5, 4, 3, 2, 1]
tower_b = []
tower_c = []
# 画出初始状态的汉诺塔
draw_tower(tower_a, tower_b, tower_c)
# 移动汉诺塔
hanoi(len(tower_a), tower_a, tower_b, tower_c)
turtle.done()
```
这个代码会画出一个初始状态为6个盘子的汉诺塔,并将其移动到另一个塔上。你可以根据需要修改盘子的数量和初始状态。
阅读全文