blob: 5e9c27b53675981a277f765bb3f23057a4887c47 [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 *
Terry Jan Reedyf51531e2014-06-22 01:18:54 -040021from turtle import Terminator # not in __all__
Martin v. Löwis97cf99f2008-06-10 04:44:07 +000022
23class Disc(Turtle):
24 def __init__(self, n):
25 Turtle.__init__(self, shape="square", visible=False)
26 self.pu()
27 self.shapesize(1.5, n*1.5, 2) # square-->rectangle
28 self.fillcolor(n/6., 0, 1-n/6.)
29 self.st()
30
31class Tower(list):
32 "Hanoi tower, a subclass of built-in type list"
33 def __init__(self, x):
34 "create an empty tower. x is x-position of peg"
35 self.x = x
36 def push(self, d):
37 d.setx(self.x)
38 d.sety(-150+34*len(self))
39 self.append(d)
40 def pop(self):
41 d = list.pop(self)
42 d.sety(150)
43 return d
44
45def hanoi(n, from_, with_, to_):
46 if n > 0:
47 hanoi(n-1, from_, to_, with_)
48 to_.push(from_.pop())
49 hanoi(n-1, with_, from_, to_)
50
51def play():
52 onkey(None,"space")
53 clear()
Terry Jan Reedyf51531e2014-06-22 01:18:54 -040054 try:
55 hanoi(6, t1, t2, t3)
56 write("press STOP button to exit",
57 align="center", font=("Courier", 16, "bold"))
58 except Terminator:
59 pass # turtledemo user pressed STOP
Martin v. Löwis97cf99f2008-06-10 04:44:07 +000060
61def main():
62 global t1, t2, t3
63 ht(); penup(); goto(0, -225) # writer turtle
64 t1 = Tower(-250)
65 t2 = Tower(0)
66 t3 = Tower(250)
67 # make tower of 6 discs
68 for i in range(6,0,-1):
69 t1.push(Disc(i))
70 # prepare spartanic user interface ;-)
71 write("press spacebar to start game",
72 align="center", font=("Courier", 16, "bold"))
73 onkey(play, "space")
74 listen()
75 return "EVENTLOOP"
76
77if __name__=="__main__":
78 msg = main()
79 print(msg)
80 mainloop()