turtle库实现汉诺塔

import turtle
turtle.screensize(800,800) class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) ==
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
if not self.isEmpty():
return self.items[len(self.items) - ]
def size(self):
return len(self.items) def drawpole_3():#画出汉诺塔的poles
t = turtle.Turtle()
t.hideturtle()
def drawpole_1(k):
t.up()
t.pensize()
t.speed()
t.goto(*(k-), )
t.down()
t.goto(*(k-), -)
t.goto(*(k-)-, -)
t.goto(*(k-)+, -)
drawpole_1()#画出汉诺塔的poles[0]
drawpole_1()#画出汉诺塔的poles[1]
drawpole_1()#画出汉诺塔的poles[2] def creat_plates(n):#制造n个盘子
plates=[turtle.Turtle() for i in range(n)]
for i in range(n):
plates[i].up()
plates[i].hideturtle()
plates[i].shape("square")
plates[i].shapesize(,-i)
plates[i].goto(-,-+*i)
plates[i].showturtle()
return plates def pole_stack():#制造poles的栈
poles=[Stack() for i in range()]
return poles def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子plates[mov]从poles[fp]移到poles[tp]
mov=poles[fp].peek()
plates[mov].goto((fp-)*,)
plates[mov].goto((tp-)*,)
l=poles[tp].size()#确定移动到底部的高度(恰好放在原来最上面的盘子上面)
plates[mov].goto((tp-)*,-+*l) def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子
if height >= :
moveTower(plates,poles,height-,fromPole,withPole,toPole)
moveDisk(plates,poles,fromPole,toPole)
poles[toPole].push(poles[fromPole].pop())
moveTower(plates,poles,height-,withPole,toPole,fromPole) myscreen=turtle.Screen()
drawpole_3()
n=int(input("请输入汉诺塔的层数并回车:\n"))
plates=creat_plates(n)
poles=pole_stack()
for i in range(n):
poles[].push(i)
moveTower(plates,poles,n,,,)
myscreen.exitonclick() 执行完毕:
turtle库实现汉诺塔

turtle库实现汉诺塔

 turtle库实现汉诺塔
上一篇:__FILE__,__LINE__,FUNCTION__


下一篇:用turtle库显示汉诺塔问题的过程