
# lsys.py
# Benjamin Bengfort
# https://paulbourke.net/fractals/lsys/
# https://gist.github.com/bbengfort/11183420
# https://users.math.yale.edu/public_html/People/frame/Fractals/IntroToFrac/InitGen/LSystems/LSysGallery/LSysGallery.html

# input: 2 or 3

'''
Draw an L-System with Python's turtle graphics library.
The L-system is defined in terms of a single axiom, 'F' rule, 
and a user-supplied level. 

'''

import turtle
from reader import *


DIST = 10

OPS = {'+', '-', '[', ']'}


def expand(startStr, level, rule):
  s = startStr
  for i in range(0, level):
    s = translate(s, rule)
  return s

def translate(str, rule):
  s = ""
  for ch in str:
    if ch in OPS:
      s += ch
    elif ch == 'F':
      s += rule
    else:
      print("Unknown character:", ch)
  return s




def draw(t, cmds):
  stack  = []         # For tracking turtle positions
  t.left(90)         # Point up instead of right

  for i in range(len(cmds)):
    ch = cmds[i]

    if ch == 'F':
      t.fd(DIST)

    elif ch == 'f':
      t.up()
      t.fd(DIST)
      t.down()

    elif ch == '+':
      t.left(angle)

    elif ch == '-':
      t.right(angle)

    elif ch == '[':
      stack.append((t.heading(), t.pos()))

    elif ch == ']':
      head, pos = stack.pop()
      t.up()
      t.goto(pos)
      t.setheading(head)
      t.down()

    else:
      print(f"Unknown command at pos {i}: \'{ch}\'")


# -------------- main ------------------

'''
axiom = "F-F-F-F"
rule = "F-F+F+FF-F-F+F"
'''

'''
axiom = "F+F+F+F"
rule = "FF+F+F+F+F+F-F"
'''

'''
axiom = "F+F+F+F"
rule = "FF+F++F+F"
'''

'''
axiom = "F+F+F+F"
rule = "FF+F+F+F+FF"
'''

fnm = input("fnm=? ")
reader = readVals("lsys/"+fnm+".txt")
axiom = readString(reader)
print("axiom:", axiom)
rule = readString(reader)
print("rule:", rule)
angle = readFloat(reader)
print("angle:", angle)

print()
level = int(input("level? "))

cmds = expand(axiom, level, rule)
# print(cmds)

t   = turtle.Turtle()
scr = t.screen
scr.title('Turtle L-system')
t.hideturtle()       # Don't show the turtle
t.speed(0)         # Make the turtle faster

draw(t, cmds)
print("Drawing finished...")

scr.exitonclick()

