2018-05-16 回答
系统自带的演示代码,可以研究一下
#!/usr/bin/env python3
""" turtle-example-suite:
tdemo_minimal_hanoi.py
a minimal 'towers of hanoi' animation:
a tower of 6 discs is transferred from the
left to the right peg.
an imho quite elegant and concise
implementation using a tower class, which
is derived from the built-in type list.
discs are turtles with shape "square", but
stretched to rectangles by shapesize()
---------------------------------------
to exit press stop button
---------------------------------------
"""
from turtle import *
class disc(turtle):
def __init__(self, n):
turtle.__init__(self, shape="square", visible=false)
self.pu()
self.shapesize(1.5, n*1.5, 2) # square-->rectangle
self.fillcolor(n/6., 0, 1-n/6.)
self.st()
class tower(list):
"hanoi tower, a subclass of built-in type list"
def __init__(self, x):
"create an empty tower. x is x-position of peg"
self.x = x
def push(self, d):
d.setx(self.x)
d.sety(-150+34*len(self))
self.append(d)
def pop(self):
d = list.pop(self)
d.sety(150)
return d
def hanoi(n, from_, with_, to_):
if n > 0:
hanoi(n-1, from_, to_, with_)
to_.push(from_.pop())
hanoi(n-1, with_, from_, to_)
def play():
onkey(none,"space")
clear()
try:
hanoi(6, t1, t2, t3)
write("press stop button to exit",
align="center", font=("courier", 16, "bold"))
except terminator:
pass # turtledemo user pressed stop
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
t1 = tower(-250)
t2 = tower(0)
t3 = tower(250)
# make tower of 6 discs
for i in range(6,0,-1):
t1.push(disc(i))
# prepare spartanic user interface ;-)
write("press spacebar to start game",
align="center", font=("courier", 16, "bold"))
onkey(play, "space")
listen()
return "eventloop"
if __name__=="__main__":
msg = main()
print(msg)
mainloop()