How to realize Hanoi tower with Python

Time:2020-4-3

Using animation to realize Hanoi Tower problem:

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(): draw the poles of Hanoi Tower
    t = turtle.Turtle()
    t.hideturtle()
    def drawpole_1(k):
        t.up()
        t.pensize(10)
        t.speed(100)
        t.goto(400*(k-1), 100)
        t.down()
        t.goto(400*(k-1), -100)
        t.goto(400*(k-1)-20, -100)
        t.goto(400*(k-1)+20, -100)
    Drawpole 1 (0) draw the poles of Hanoi tower [0]
    Drawpole 1 (1) draw the poles of Hanoi tower [1]
    Draw pole 1 (2) draw poles of Hanoi tower [2]

Def create? Plates (n):? Make n plates
    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(1,8-i)
        plates[i].goto(-400,-90+20*i)
        plates[i].showturtle()
    return plates

Def pole? Stack(): the stack that makes poles
    poles=[Stack() for i in range(3)]
    return poles

Def movedisk (plates, poles, FP, TP): move plates [mov] at the top of poles [FP] from poles [FP] to poles [TP]
    mov=poles[fp].peek()
    plates[mov].goto((fp-1)*400,150)
    plates[mov].goto((tp-1)*400,150)
    L = poles [TP]. Size() ා determine the height to move to the bottom (just above the original top plate)
    plates[mov].goto((tp-1)*400,-90+20*l)

Def movetower (plates, poles, height, frompole, topole, withpole): ාrecursively put plates
    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 ("please enter the number of floors of the Hanoi Tower and enter: \ n"))
plates=creat_plates(n)
poles=pole_stack()
for i in range(n):
    poles[0].push(i)
moveTower(plates,poles,n,0,2,1)
myscreen.exitonclick()