willingc

allendowneyexaample

May 9th, 2015
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. """This module contains code from
  2. Think Python by Allen B. Downey
  3. http://thinkpython.com
  4.  
  5. Copyright 2012 Allen B. Downey
  6. License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
  7.  
  8. """
  9.  
  10. import math
  11.  
  12. try:
  13.     # see if Swampy is installed as a package
  14.     from swampy.TurtleWorld import *
  15. except ImportError:
  16.     # otherwise see if the modules are on the PYTHONPATH
  17.     from TurtleWorld import *
  18.  
  19.  
  20. def square(t, length):
  21.     """Draws a square with sides of the given length.
  22.  
  23.    Returns the Turtle to the starting position and location.
  24.    """
  25.     for i in range(4):
  26.         fd(t, length)
  27.         lt(t)
  28.  
  29.  
  30. def polyline(t, n, length, angle):
  31.     """Draws n line segments.
  32.  
  33.    t: Turtle object
  34.    n: number of line segments
  35.    length: length of each segment
  36.    angle: degrees between segments
  37.    """
  38.     for i in range(n):
  39.         fd(t, length)
  40.         lt(t, angle)
  41.  
  42.  
  43. def polygon(t, n, length):
  44.     """Draws a polygon with n sides.
  45.  
  46.    t: Turtle
  47.    n: number of sides
  48.    length: length of each side.
  49.    """
  50.     angle = 360.0/n
  51.     polyline(t, n, length, angle)
  52.  
  53.  
  54. def arc(t, r, angle):
  55.     """Draws an arc with the given radius and angle.
  56.  
  57.    t: Turtle
  58.    r: radius
  59.    angle: angle subtended by the arc, in degrees
  60.    """
  61.     arc_length = 2 * math.pi * r * abs(angle) / 360
  62.     n = int(arc_length / 4) + 1
  63.     step_length = arc_length / n
  64.     step_angle = float(angle) / n
  65.  
  66.     # making a slight left turn before starting reduces
  67.     # the error caused by the linear approximation of the arc
  68.     lt(t, step_angle/2)
  69.     polyline(t, n, step_length, step_angle)
  70.     rt(t, step_angle/2)
  71.  
  72.  
  73. def circle(t, r):
  74.     """Draws a circle with the given radius.
  75.  
  76.    t: Turtle
  77.    r: radius
  78.    """
  79.     arc(t, r, 360)
  80.  
  81.  
  82. # the following condition checks whether we are
  83. # running as a script, in which case run the test code,
  84. # or being imported, in which case don't.
  85.  
  86. if __name__ == '__main__':
  87.     world = TurtleWorld()    
  88.  
  89.     bob = Turtle()
  90.     bob.delay = 0.001
  91.  
  92.     # draw a circle centered on the origin
  93.     radius = 100
  94.     pu(bob)
  95.     fd(bob, radius)
  96.     lt(bob)
  97.     pd(bob)
  98.     circle(bob, radius)
  99.  
  100.     wait_for_user()
Advertisement
Add Comment
Please, Sign In to add comment