给我编写一个可视化的汉诺塔
时间: 2023-11-21 14:04:07 浏览: 81
纯javascript实现汉诺塔可视化小游戏
好的,以下是一个基于 Python 和 Turtle 模块的汉诺塔可视化程序:
```python
import turtle
# 设置窗口大小和标题
win = turtle.Screen()
win.setup(width=600, height=400)
win.title("汉诺塔")
# 定义三个柱子
pillar1 = turtle.Turtle()
pillar2 = turtle.Turtle()
pillar3 = turtle.Turtle()
# 设置柱子的位置和大小
pillar1.penup()
pillar1.goto(-200, -100)
pillar1.pendown()
pillar1.pensize(5)
pillar1.left(90)
pillar1.forward(200)
pillar2.penup()
pillar2.goto(0, -100)
pillar2.pendown()
pillar2.pensize(5)
pillar2.left(90)
pillar2.forward(200)
pillar3.penup()
pillar3.goto(200, -100)
pillar3.pendown()
pillar3.pensize(5)
pillar3.left(90)
pillar3.forward(200)
# 定义盘子
disk1 = turtle.Turtle()
disk2 = turtle.Turtle()
disk3 = turtle.Turtle()
# 设置盘子的大小和颜色
disk1.shapesize(stretch_wid=1, stretch_len=3)
disk1.color("red")
disk2.shapesize(stretch_wid=1, stretch_len=2.5)
disk2.color("green")
disk3.shapesize(stretch_wid=1, stretch_len=2)
disk3.color("blue")
# 设置盘子的位置
disk1.penup()
disk1.goto(-200, -50)
disk2.penup()
disk2.goto(-200, -25)
disk3.penup()
disk3.goto(-200, 0)
# 定义移动盘子的函数
def move_disk(disk, from_pillar, to_pillar):
disk.penup()
disk.goto(to_pillar.pos())
disk.pendown()
disk.goto(to_pillar.pos() + (0, len(to_pillar) * 20))
to_pillar.push(disk, from_pillar)
# 定义柱子类
class Pillar:
def __init__(self):
self.stack = []
self.turtle = None
def set_turtle(self, turtle):
self.turtle = turtle
def pos(self):
return self.turtle.pos()
def push(self, disk, from_pillar):
self.stack.append(disk)
from_pillar.pop()
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
return None
def __len__(self):
return len(self.stack)
# 创建柱子对象
pillar1 = Pillar()
pillar2 = Pillar()
pillar3 = Pillar()
# 设置柱子的 Turtle 对象
pillar1.set_turtle(pillar1)
pillar2.set_turtle(pillar2)
pillar3.set_turtle(pillar3)
# 将盘子放在第一个柱子上
pillar1.push(disk3, pillar1)
pillar1.push(disk2, pillar1)
pillar1.push(disk1, pillar1)
# 定义递归函数
def hanoi(n, from_pillar, to_pillar, via_pillar):
if n > 0:
hanoi(n-1, from_pillar, via_pillar, to_pillar)
move_disk(from_pillar.pop(), from_pillar, to_pillar)
hanoi(n-1, via_pillar, to_pillar, from_pillar)
# 开始移动盘子
hanoi(3, pillar1, pillar3, pillar2)
# 等待用户关闭窗口
turtle.done()
```
运行程序后,会弹出一个窗口,显示三个柱子和三个盘子。程序会自动将三个盘子从第一个柱子移动到第三个柱子,然后结束程序。你可以根据自己的需要修改程序中的参数,比如盘子的数量、颜色、大小等。
阅读全文