【PYTHON】用turtle画一朵花

《像计算机科学家一样思考PYTHON》练习4-2

http://www.greenteapress.com/thinkpython2/code/flower.py

附图

 

 1 #mypolygon.py
 2 import turtle
 3 import math
 4 
 5 def square(t, length):
 6     """Draws a square with sides of the given length.
 7 
 8     Returns the Turtle to the starting position and location.
 9     """
10     for i in range(4):
11         t.fd(length)
12         t.lt(90)
13 
14 
15 def polyline(t, n, length, angle):
16     """Draws n line segments.
17 
18     t: Turtle object
19     n: number of line segments
20     length: length of each segment
21     angle: degrees between segments
22     """
23     for i in range(n):
24         t.fd(length)
25         t.lt(angle)
26 
27 
28 def polygon(t, n, length):
29     """Draws a polygon with n sides.
30 
31     t: Turtle
32     n: number of sides
33     length: length of each side.
34     """
35     angle = 360.0/n
36     polyline(t, n, length, angle)
37 
38 
39 def arc(t, r, angle):
40     """Draws an arc with the given radius and angle.
41 
42     t: Turtle
43     r: radius
44     angle: angle subtended by the arc, in degrees
45     """
46     arc_length = 2 * math.pi * r * abs(angle) / 360
47     n = int(arc_length / 4) + 1
48     step_length = arc_length / n
49     step_angle = float(angle) / n
50 
51     # making a slight left turn before starting reduces
52     # the error caused by the linear approximation of the arc
53     t.lt(step_angle/2)
54     polyline(t, n, step_length, step_angle)
55     t.rt(step_angle/2)
56 
57 
58 def circle(t, r):
59     """Draws a circle with the given radius.
60 
61     t: Turtle
62     r: radius
63     """
64     arc(t, r, 360)
65 
66 # the following condition checks whether we are
67 # running as a script, in which case run the test code,
68 # or being imported, in which case don't.
69 
70 if __name__ == '__main__':
71     bob = turtle.Turtle()
72 
73     # draw a circle centered on the origin
74     radius = 100
75     bob.pu()
76     bob.fd(radius)
77     bob.lt(90)
78     bob.pd()
79     arc(bob, radius,100)
80 
81     # wait for the user to close the window
82     turtle.mainloop()

#
flower.py import turtle from mypolygon import arcdef move(t, length): t.pu() t.fd(length) t.pd() def petal(t, r, angle):#绘制花瓣 for i in range(2): arc(t, r, angle) t.lt(180-angle) def flower(t, n, r, angle): for i in range(n): petal(t, r, angle) t.lt(360.0/n) bob = turtle.Turtle() move(bob, -100) flower(bob, 7, 60.0, 60.0) move(bob, 100) flower(bob, 10, 40.0, 80.0) move(bob, 100) flower(bob, 20, 140.0, 20.0) bob.hideturtle() turtle.mainloop()

 

posted @ 2017-09-12 16:14  kikii233  阅读(2989)  评论(0编辑  收藏  举报