1 mport turtle 2 3 class Stack: 4 def __init__(self): 5 self.items = [] 6 def isEmpty(self): 7 return len(self.items) == 0 8 def push(self, item): 9 self.items.append(item) 10 def pop(self): 11 return self.items.pop() 12 def peek(self): 13 if not self.isEmpty(): 14 return self.items[len(self.items) - 1] 15 def size(self): 16 return len(self.items) 17 18 def drawpole_3():#画出汉诺塔的poles 19 t = turtle.Turtle() 20 t.hideturtle() 21 def drawpole_1(k): 22 t.up() 23 t.pensize(10) 24 t.speed(100) 25 t.goto(400*(k-1), 100) 26 t.down() 27 t.goto(400*(k-1), -100) 28 t.goto(400*(k-1)-20, -100) 29 t.goto(400*(k-1)+20, -100) 30 drawpole_1(0)#画出汉诺塔的poles[0] 31 drawpole_1(1)#画出汉诺塔的poles[1] 32 drawpole_1(2)#画出汉诺塔的poles[2] 33 34 def creat_plates(n):#制造n个盘子 35 plates=[turtle.Turtle() for i in range(n)] 36 for i in range(n): 37 plates[i].up() 38 plates[i].hideturtle() 39 plates[i].shape("square") 40 plates[i].shapesize(1,8-i) 41 plates[i].goto(-400,-90+20*i) 42 plates[i].showturtle() 43 return plates 44 45 def pole_stack():#制造poles的栈 46 poles=[Stack() for i in range(3)] 47 return poles 48 49 def moveDisk(plates,poles,fp,tp):#把poles[fp]顶端的盘子plates[mov]从poles[fp]移到poles[tp] 50 mov=poles[fp].peek() 51 plates[mov].goto((fp-1)*400,150) 52 plates[mov].goto((tp-1)*400,150) 53 l=poles[tp].size()#确定移动到底部的高度(恰好放在原来最上面的盘子上面) 54 plates[mov].goto((tp-1)*400,-90+20*l) 55 56 def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子 57 if height >= 1: 58 moveTower(plates,poles,height-1,fromPole,withPole,toPole) 59 moveDisk(plates,poles,fromPole,toPole) 60 poles[toPole].push(poles[fromPole].pop()) 61 moveTower(plates,poles,height-1,withPole,toPole,fromPole) 62 63 myscreen=turtle.Screen() 64 drawpole_3() 65 n=int(input("请输入汉诺塔的层数并回车:")) 66 plates=creat_plates(n) 67 poles=pole_stack() 68 for i in range(n): 69 poles[0].push(i) 70 moveTower(plates,poles,n,0,2,1) 71 myscreen.exitonclick()
一、汉诺塔五层:
二、汉诺塔三层: