首页 > 编程语言 > 详细

python 汉诺塔程序+用tutle写出库动图

时间:2020-03-29 23:39:22      阅读:80      评论:0      收藏:0      [点我收藏+]
n=input("输入汉诺塔碟子总数")
def move(n,a,b,c): if n==1: print(a,‘->‘,c) else: move(n-1,a,c,b) move(1,a,b,c) move(n-1,b,a,c)

动图:
import turtle
class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return len(self.items) == 0
    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) - 1]
    def size(self):
        return len(self.items)
 
def drawpole_3():#画出汉诺塔的poles
    = turtle.Turtle()
    t.hideturtle()
    def drawpole_1(k):
        t.up()
        t.pensize(10)
        t.speed(100)
        t.goto(250*(k-1), 100)
        t.down()
        t.goto(250*(k-1), -100)
        t.goto(250*(k-1)-20-100)
        t.goto(250*(k-1)+20-100)
    drawpole_1(0)#画出汉诺塔的polesA
    drawpole_1(1)#画出汉诺塔的polesB
    drawpole_1(2)#画出汉诺塔的polesC
 
def creat_plates(n):#制造n个盘子
    plates=[turtle.Turtle() for in range(n)]
    for in range(n):
        plates[i].up()
        plates[i].hideturtle()
        plates[i].shape("square")
        plates[i].shapesize(1,9-i)
        plates[i].goto(-250,-90+20*i)
        plates[i].showturtle()
    return plates
 
def pole_stack():#制造poles的栈
    poles=[Stack() for in range(3)]
    return poles
 
def moveDisk(plates,poles,fp,tp):#把polesA顶端的盘子plates[mov]从polesA移到polesC
    mov=poles[fp].peek()
    plates[mov].goto((fp-1)*250,150)
    plates[mov].goto((tp-1)*250,150)
    l=poles[tp].size()        #确定移动到底部的高度(恰好放在原来最上面的盘子上面)
    plates[mov].goto((tp-1)*250,-90+20*l)
 
def moveTower(plates,poles,height,fromPole, toPole, withPole):#递归放盘子
    if height >= 1:
        moveTower(plates,poles,height-1,fromPole,withPole,toPole)
        moveDisk(plates,poles,fromPole,toPole)
        poles[toPole].push(poles[fromPole].pop())
        moveTower(plates,poles,height-1,withPole,toPole,fromPole)
 
myscreen=turtle.Screen()
drawpole_3()
n=int(input("请输入汉诺塔的层数并回车:\n"))
plates=creat_plates(n)
poles=pole_stack()
for in range(n):
    poles[0].push(i)
moveTower(plates,poles,n,0,2,1)
myscreen.exitonclick()

python 汉诺塔程序+用tutle写出库动图

原文:https://www.cnblogs.com/yabaodamowang/p/12595411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!