汉罗塔

一.汉罗塔

       汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。

 

二.代码

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

 

 

三.演示

 

posted @ 2019-03-27 23:03  落尘一缕沙  阅读(1096)  评论(0编辑  收藏  举报