#Project4 Dragon Curve Solution # Josh Fuerst 10/10/12 # # extended to generate dragon curve on th fly # extended to do bracketed L0 systems # Hoffmann October 2012 # # coordinate system left native # from PIL import Image from PIL import ImageDraw import math import random # change heading by angle a, but # keep headings between -180 and +180 # all angles in degrees as int # reference direction is North def adjState(xya, a): dr = xya[2]+a while dr > 180: dr -= 360 while dr < -180: dr += 360 return (xya[0], xya[1], dr) # forward line drawn from current state and heading # drw is the drawing object # inverted y direction by using -length * cosine def drawLineAngle(state, length, drw, color): x0 = state[0] y0 = state[1] dr = state[2] al = math.radians(dr) cs = math.cos(al) sn = math.sin(al) x1 = x0 + length*sn y1 = y0 - length*cs drw.line((x0,y0,int(x1),int(y1)),color) return (x1,y1,dr) # interpret string for drawing def mapDraw(str,img,gen,ang): state = (img.size[0]/2, img.size[1]/2, 0) # init turtle state stack = [] drw = ImageDraw.Draw(img) if gen<3: line = 20 elif gen<4: line = 20 elif gen<5: line = 10 else: line = 5 #print('string arg', str) for ch in str: if ch == 'F': state = drawLineAngle(state,line,drw,(0,0,0)) elif ch == '+': state = adjState(state, ang) elif ch == '-': state = adjState(state,-ang) elif ch == '[': stack.append(state) elif ch == ']': state = stack.pop() # else we ignore it #img.show() del drw def rewrit(strng, ruleindex): L = [] for ch in strng: if ch in rewrite[ruleindex]: L.append(rewrite[ruleindex][ch]) else: L.append(ch) strng = "".join(x for x in L) print(strng) return strng def Lsystem1(gen, img): # this is a fixed L-system, no generality strng = 'F' for g in range(gen): strng = rewrit(strng,0) mapDraw(strng,img,gen,22) return def Lsystem2(gen, img): # this is a fixed L-system, no generality strng = 'FX' for g in range(gen): strng = rewrit(strng,1) mapDraw(strng,img,gen,90) return def control(): print("type command --") print(" 0 - exit") print(" 1 - grass") print(" 2 - dragon") cmd = eval(input(":: ")) if cmd != 0: gen = eval(input("generation: ")) if gen<1: gen=1 if gen>15: gen=15 else: gen = 0 return cmd, gen # rewrite rules rewrite = [{ 'F':'F[-F]F[+F][F]' }, { 'X':'X+YF', 'Y':'FX-Y' }] def main(): # launch dialogue c,g = control() while c > 0: if c > 3: break img = Image.new('RGB',(300,400),'white') if c==1: print("Lsys 1",g) Lsystem1(g, img) img.show() #img.save("Lsys_image_" + str(g) + ".jpeg") elif c == 2: print("Lsys 2",g) Lsystem2(g, img) img.show() else: print("done") c,g = control() #break print("image saved") main()