Python画汉诺塔

源码:

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

 

效果图:

在这里插入图片描述
在这里插入图片描述

 

posted @ 2021-02-16 13:08  BugMiaowu2021  阅读(137)  评论(0编辑  收藏  举报