| 1 |
"""turtledemo/minimal_hanoi.py |
| 2 |
|
| 3 |
A minimal 'Towers of Hanoi' animation: |
| 4 |
A tower of 6 discs is transferred from the |
| 5 |
left to the right peg. |
| 6 |
|
| 7 |
An imho quite elegant and concise |
| 8 |
implementation using a tower class, which |
| 9 |
is derived from the built-in type list. |
| 10 |
|
| 11 |
Discs are turtles with shape "square", but |
| 12 |
stretched to rectangles by shapesize() |
| 13 |
""" |
| 14 |
from turtle import * |
| 15 |
|
| 16 |
class Disc(Turtle): |
| 17 |
def __init__(self, n): |
| 18 |
Turtle.__init__(self, shape="square", visible=False) |
| 19 |
self.pu() |
| 20 |
self.shapesize(1.5, n*1.5, 2) # square-->rectangle |
| 21 |
self.fillcolor(n/6., 0, 1-n/6.) |
| 22 |
self.st() |
| 23 |
|
| 24 |
class Tower(list): |
| 25 |
"Hanoi tower, a subclass of built-in type list" |
| 26 |
def __init__(self, x): |
| 27 |
"create an empty tower. x is x-position of peg" |
| 28 |
self.x = x |
| 29 |
def push(self, d): |
| 30 |
d.setx(self.x) |
| 31 |
d.sety(-150+34*len(self)) |
| 32 |
self.append(d) |
| 33 |
def pop(self): |
| 34 |
d = list.pop(self) |
| 35 |
d.sety(150) |
| 36 |
return d |
| 37 |
|
| 38 |
def hanoi(n, from_, with_, to_): |
| 39 |
if n > 0: |
| 40 |
hanoi(n-1, from_, to_, with_) |
| 41 |
to_.push(from_.pop()) |
| 42 |
hanoi(n-1, with_, from_, to_) |
| 43 |
|
| 44 |
def play(): |
| 45 |
onkey(None,"space") |
| 46 |
clear() |
| 47 |
try: |
| 48 |
hanoi(6, t1, t2, t3) |
| 49 |
write("press STOP button to exit", |
| 50 |
align="center", font=("Courier", 16, "bold")) |
| 51 |
except Terminator: |
| 52 |
pass # turtledemo user pressed STOP |
| 53 |
|
| 54 |
def main(): |
| 55 |
global t1, t2, t3 |
| 56 |
ht(); penup(); goto(0, -225) # writer turtle |
| 57 |
t1 = Tower(-250) |
| 58 |
t2 = Tower(0) |
| 59 |
t3 = Tower(250) |
| 60 |
# make tower of 6 discs |
| 61 |
for i in range(6,0,-1): |
| 62 |
t1.push(Disc(i)) |
| 63 |
# prepare spartanic user interface ;-) |
| 64 |
write("press spacebar to start game", |
| 65 |
align="center", font=("Courier", 16, "bold")) |
| 66 |
onkey(play, "space") |
| 67 |
listen() |
| 68 |
return "EVENTLOOP" |
| 69 |
|
| 70 |
if __name__=="__main__": |
| 71 |
msg = main() |
| 72 |
print(msg) |
| 73 |
mainloop() |