用Python画出汉诺塔
时间: 2023-11-05 08:53:18 浏览: 100
当然可以!下面是使用Python语言绘制汉诺塔的代码:
```python
import turtle
def draw_tower(x, y, width, height):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(width/2)
turtle.left(90)
turtle.forward(height)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(height)
turtle.left(90)
turtle.forward(width/2)
def draw_disk(x, y, width):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(width/2)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(width/2)
def hanoi(n, source, target, auxiliary):
if n > 0:
hanoi(n-1, source, auxiliary, target)
disk_width = n * 20
draw_disk(-disk_width/2, (n-1) * 20 - 150, disk_width)
hanoi(n-1, auxiliary, target, source)
turtle.speed(0)
# 绘制底座
draw_tower(-100, -150, 200, 10)
# 设置初始位置
turtle.penup()
turtle.goto(-100, -140)
# 绘制汉诺塔的盘子
hanoi(5, 'A', 'C', 'B')
turtle.done()
```
这段代码首先使用`turtle`库绘制了汉诺塔的底座和盘子。然后通过递归算法`hanoi`来移动和绘制盘子。你可以根据需要调整参数`hanoi(5, 'A', 'C', 'B')`中的数字来改变盘子的数量。执行代码后,将会在窗口中显示绘制好的汉诺塔图形。
阅读全文