comparison CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/turtledemo/minimal_hanoi.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
comparison
equal deleted inserted replaced
67:0e9998148a16 69:33d812a61356
1 #!/usr/bin/env python3
2 """ turtle-example-suite:
3
4 tdemo_minimal_hanoi.py
5
6 A minimal 'Towers of Hanoi' animation:
7 A tower of 6 discs is transferred from the
8 left to the right peg.
9
10 An imho quite elegant and concise
11 implementation using a tower class, which
12 is derived from the built-in type list.
13
14 Discs are turtles with shape "square", but
15 stretched to rectangles by shapesize()
16 ---------------------------------------
17 To exit press STOP button
18 ---------------------------------------
19 """
20 from turtle import *
21
22 class 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
30 class 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
44 def 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
50 def play():
51 onkey(None,"space")
52 clear()
53 try:
54 hanoi(6, t1, t2, t3)
55 write("press STOP button to exit",
56 align="center", font=("Courier", 16, "bold"))
57 except Terminator:
58 pass # turtledemo user pressed STOP
59
60 def main():
61 global t1, t2, t3
62 ht(); penup(); goto(0, -225) # writer turtle
63 t1 = Tower(-250)
64 t2 = Tower(0)
65 t3 = Tower(250)
66 # make tower of 6 discs
67 for i in range(6,0,-1):
68 t1.push(Disc(i))
69 # prepare spartanic user interface ;-)
70 write("press spacebar to start game",
71 align="center", font=("Courier", 16, "bold"))
72 onkey(play, "space")
73 listen()
74 return "EVENTLOOP"
75
76 if __name__=="__main__":
77 msg = main()
78 print(msg)
79 mainloop()