Last active
April 2, 2018 19:50
-
-
Save m-ammar/0ee3223e4510f64d55da7b6e4b399a7b to your computer and use it in GitHub Desktop.
Exercise 4-2. Write an appropriately general set of functions that can draw flowers as in https://www.safaribooksonline.com/library/view/think-python-2nd/9781491939406/assets/tnkp_0401.png
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import turtle | |
def polyline(obj, length, sides, angle): | |
for i in range(sides): | |
obj.fd(length) | |
obj.lt(angle) | |
def arc(t, radius, angle): | |
arc_length = 2 * math.pi * radius * angle / 360 | |
sides = int(arc_length / 3) + 1 | |
step_length = arc_length / sides | |
step_angle = angle / sides | |
polyline(obj = t, length = step_length, sides = sides, angle = step_angle) | |
def petal(t, r, angle): | |
for i in range(2): | |
arc(t, r, angle) | |
t.lt(180.0-angle) | |
def flower(t, n, r, angle): | |
""" | |
t: turtle | |
n: number of petals in the flower | |
r: radius of the arcs | |
angle: angle that subtends the arc | |
""" | |
for i in range(n): | |
petal(t, r, angle) | |
t.lt(360.0/n) | |
def move_turtle(t, length): | |
t.pu() | |
t.fd(length) | |
t.pd() | |
bob = turtle.Turtle() | |
move_turtle(bob, -200) | |
flower(bob, 7, 60.0, 60.0) | |
move_turtle(bob, 200) | |
flower(bob, 10, 50.0, 70.0) | |
move_turtle(bob, 200) | |
flower(bob, 20, 120.0, 20.0) | |
bob.hideturtle() | |
turtle.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment