ยปCore Development>Code coverage>Lib/turtledemo/minimal_hanoi.py

Python code coverage for Lib/turtledemo/minimal_hanoi.py

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