《像计算机科学家一样思考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 object19 n: number of line segments20 length: length of each segment21 angle: degrees between segments22 """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: Turtle32 n: number of sides33 length: length of each side.34 """35 angle = 360.0/n36 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: Turtle43 r: radius44 angle: angle subtended by the arc, in degrees45 """46 arc_length = 2 * math.pi * r * abs(angle) / 36047 n = int(arc_length / 4) + 148 step_length = arc_length / n49 step_angle = float(angle) / n50 51 # making a slight left turn before starting reduces52 # the error caused by the linear approximation of the arc53 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: Turtle62 r: radius63 """64 arc(t, r, 360)65 66 # the following condition checks whether we are67 # 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 origin74 radius = 10075 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 window82 turtle.mainloop()
#flower.pyimport turtlefrom 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()