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