toy-programs

git clone git://git.codymlewis.com/toy-programs.git
Log | Files | Refs | README | LICENSE

Fractals.py (2211B)


      1 #!/usr/bin/env python3
      2 
      3 import argparse
      4 import turtle
      5 import tkinter
      6 
      7 from PIL import Image
      8 
      9 '''
     10 Draw a square fractal using turtle
     11 
     12 Author: Cody Lewis
     13 Date: 2019-04-19
     14 '''
     15 
     16 
     17 SPEED = 0
     18 
     19 
     20 class ThisTurtle(turtle.Turtle):
     21     '''
     22     Set up the turtle that draws a specific fractal.
     23     '''
     24     def __init__(self, goal):
     25         super(ThisTurtle, self).__init__()
     26         self.color("green")
     27         self.speed(SPEED)
     28         self.goal = goal
     29         self.forward_dist = 3
     30         self.hideturtle()
     31 
     32     def draw(self):
     33         '''Draw the fractal, first generation defines general shape'''
     34         omega(self, goal=self.goal)
     35         for _ in range(11):
     36             self.right(30)
     37             omega(self, goal=self.goal)
     38 
     39 
     40 def omega(cur_turtle, level=1, goal=0):
     41     '''Recursively draw proceeding generations'''
     42     if level == goal:
     43         cur_turtle.forward(cur_turtle.forward_dist)
     44     else:
     45         omega(cur_turtle, level + 1, goal)
     46         cur_turtle.right(90)
     47         omega(cur_turtle, level + 1, goal)
     48         cur_turtle.left(90)
     49         omega(cur_turtle, level + 1, goal)
     50         cur_turtle.left(90)
     51         omega(cur_turtle, level + 1, goal)
     52         cur_turtle.right(90)
     53         omega(cur_turtle, level + 1, goal)
     54         # cur_turtle.left(90)
     55         # omega(cur_turtle, level + 1, goal)
     56         # cur_turtle.left(90)
     57         # omega(cur_turtle, level + 1, goal)
     58         omega(cur_turtle, level + 1, goal)
     59 
     60 
     61 if __name__ == '__main__':
     62     PARSER = argparse.ArgumentParser(description="Draw a square fractal using turtle.")
     63     PARSER.add_argument(dest="goal", metavar="GOAL", action="store", nargs="?", type=int, default=1,
     64                         help="The number of generations of the fractal")
     65 
     66     ARGS = PARSER.parse_args()
     67     GOAL = ARGS.goal
     68     if GOAL < 1:
     69         GOAL = 1
     70     print(f"Drawing a fractal with {GOAL} generation{(lambda: 's' if GOAL > 1 else '')()}")
     71     TURTLE = ThisTurtle(GOAL)
     72     TURTLE.draw()
     73     print("Saving fractal...")
     74     TURTLE.getscreen().getcanvas().postscript(file='fractal.ps')
     75     IMG = Image.open("fractal.ps")
     76     IMG.save("fractal.png")
     77     try:
     78         turtle.exitonclick()
     79         turtle.mainloop()
     80     except turtle.Terminator:
     81         print("bye.")