Python汉诺塔可视化代码
时间: 2024-12-31 21:09:12 浏览: 8
在Python中,可以使用Turtle模块或者Pygame等图形库来实现汉诺塔的可视化动画。以下是一个简单的使用Turtle模块的例子:
```python
import turtle
def move_disk(from_pole, to_pole):
disk = turtle.Turtle()
disk.shape("square")
disk.color("blue")
disk.penup()
disk.goto(to_pole)
disk.pendown()
for _ in range(from_pole.color("red").shape("circle") + 1):
disk.forward(100)
disk.right(90)
def hanoi(n, source, auxiliary, target):
if n > 0:
# Move n - 1 disks from source to auxiliary using target as intermediate
hanoi(n - 1, source, target, auxiliary)
# Move the nth disk from source to target
move_disk(source, target)
# Move the n - 1 disks that we left on auxiliary to target
hanoi(n - 1, auxiliary, source, target)
# Set up the poles and start the animation
turtle.speed(0) # Faster animations
hanoi(3, "A", "B", "C")
turtle.done()
```
在这个代码中,我们定义了两个函数,`move_disk`用于移动单个盘子,`hanoi`则递归地实现了整个汉诺塔游戏。最后,我们创建了一个Turtle实例并设置速度为0来加快动画展示。
阅读全文