Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Mon Oct 1 23:57:09 2018
- What to learn in this sample:
- Encapsulation:
- Wrapping a piece of code up in a function is called encapsulation. One of the benefits of
- encapsulation is that it attaches a name to the code, which serves as a kind of documentation.
- Generalization:
- make a attribute/behavior more general by adding parameters in a function
- Refactoring:
- The process in which you rearrange a program in order to improve the following two things:
- * interfaces
- * code re-use
- @author: sam
- """
- import turtle
- import math
- # for both polygon and arc
- # Refactoring: extract the common parts from polygon(..) and arc(..)
- def polyline(t, len, sides, angle):
- # we have a number of sides, but it might not be complete to form a polygon
- # for each side, we know how long it should be by len
- # and we know after each side, how many angle we should turn by angle
- for side in range(sides):
- t.lt(angle) # improvement: to let the circle turn first
- t.fd(len)
- # draw a polygon with flexible side and length
- # generalization for sides_arc sides and length
- def polygon(t, len, sides):
- angle_for_each_side = 360.0 / sides # to see how many angle is assigned to each side
- polyline(t, len, sides, angle_for_each_side)
- # draw a square with a fixed length
- def square(t):
- square(t, 50)
- # draw a square with flexible length
- # generalization for len
- def square(t, len):
- polygon(t, len, 4)
- # draw an arc
- def arc(t, r, angle):
- circumference = 2*math.pi*r
- arc_length = circumference * (angle/360)
- sides = int(arc_length/3) + 3 # get an approximate sides according to the arc_length
- len = arc_length/sides
- angle_for_each_side = angle / sides
- polyline(t, len, sides, angle_for_each_side)
- # draw an approximate circle
- def circle(t, r):
- arc(t, r, 360)
- """
- Use cases
- """
- bob = turtle.Turtle()
- # draw a square use a turtle
- # square(bob)
- # draw a square use a turtle with a specific length
- #square(bob, 10)
- #square(bob, 150)
- # draw a n-sided polygon
- # polygon(bob, 100, 6)
- # draw an approximate circle
- circle(bob, 100)
- # draw an arc
- # using keyword arguments
- # arc(bob,r=25,angle=270)
- # arc(bob,r=75,angle=270)
- # wait for the user to close the window
- turtle.mainloop()
- # bob.pd() # ???
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement