3
# [SNIPPET_NAME: Turtle Hanoi]
4
# [SNIPPET_CATEGORIES: PyTurtle]
5
# [SNIPPET_DESCRIPTION: Turtle plays Towers of Hanoi.]
6
# [SNIPPET_DOCS: http://docs.python.org/library/turtle.html]
7
# [SNIPPET_AUTHOR: Grant Bowman <grantbow@ubuntu.com>]
8
# [SNIPPET_LICENSE: PSF]
10
""" turtle-example-suite:
12
tdemo_minimal_hanoi.py
14
A minimal 'Towers of Hanoi' animation:
15
A tower of 6 discs is transferred from the
16
left to the right peg.
18
An imho quite elegant and concise
19
implementation using a tower class, which
20
is derived from the built-in type list.
22
Discs are turtles with shape "square", but
23
stretched to rectangles by shapesize()
24
---------------------------------------
25
To exit press STOP button
26
---------------------------------------
31
def __init__(self, n):
32
Turtle.__init__(self, shape="square", visible=False)
34
self.shapesize(1.5, n*1.5, 2) # square-->rectangle
35
self.fillcolor(n/6., 0, 1-n/6.)
39
"Hanoi tower, a subclass of built-in type list"
40
def __init__(self, x):
41
"create an empty tower. x is x-position of peg"
45
d.sety(-150+34*len(self))
52
def hanoi(n, from_, with_, to_):
54
hanoi(n-1, from_, to_, with_)
56
hanoi(n-1, with_, from_, to_)
62
write("press STOP button to exit",
63
align="center", font=("Courier", 16, "bold"))
67
ht(); penup(); goto(0, -225) # writer turtle
71
# make tower of 6 discs
72
for i in range(6,0,-1):
74
# prepare spartanic user interface ;-)
75
write("press spacebar to start game",
76
align="center", font=("Courier", 16, "bold"))
81
if __name__=="__main__":