MCPcopy Create free account
hub / github.com/ActiveState/code / draw_fractal

Function draw_fractal

recipes/Python/577159_LSystem_Fractals/recipe-577159.py:25–91  ·  view source on GitHub ↗
(length, numAngle, level, initial_state, trgt, rplcmnt, trgt2, rplcmnt2)

Source from the content-addressed store, hash-verified

23 return state
24
25def draw_fractal(length, numAngle, level, initial_state, trgt, rplcmnt, trgt2, rplcmnt2):
26 global imgx, imgy
27 fractal = L_system(level, initial_state, trgt, rplcmnt, trgt2, rplcmnt2)
28 na = 2.0 * math.pi / numAngle
29 sn = []
30 cs = []
31 for i in range(numAngle):
32 sn.append(math.sin(na * i))
33 cs.append(math.cos(na * i))
34
35 # find xmin, xmax, ymin, ymax
36 x = 0.0
37 y = 0.0
38 xa = x
39 xb = x
40 ya = y
41 yb = y
42 k = 0
43 for ch in fractal:
44 if ch == 'F':
45 # turtle forward(length)
46 x += length * cs[k]
47 y += length * sn[k]
48 if x < xa:
49 xa = x
50 if x > xb:
51 xb = x
52 if y < ya:
53 ya = y
54 if y > yb:
55 yb = y
56 elif ch == '+':
57 # turtle right(angle)
58 k = (k + 1) % numAngle
59 elif ch == '-':
60 # turtle left(angle)
61 k = ((k - 1) + numAngle) % numAngle
62
63 # draw the fractal
64 imgy = round(imgy * (yb - ya) / (xb - xa)) # auto-re-adjust the aspect ratio
65 image = Image.new("L", (imgx, imgy))
66 draw = ImageDraw.Draw(image)
67 x = 0.0
68 y = 0.0
69 jx = int((x - xa) / (xb - xa) * (imgx - 1))
70 jy = int((y - ya) / (yb - ya) * (imgy - 1))
71 k = 0
72 for ch in fractal:
73 if ch == 'F':
74 # turtle forward(length)
75 x0 = x + length * cs[k]
76 y0 = y + length * sn[k]
77 jx0 = int((x - xa) / (xb - xa) * (imgx - 1))
78 jy0 = int((y - ya) / (yb - ya) * (imgy - 1))
79 draw.line ([(jx, jy),(jx0, jy0)], 255)
80 x = x0
81 y = y0
82 jx = jx0

Callers 1

recipe-577159.pyFile · 0.70

Calls 9

L_systemFunction · 0.85
rangeFunction · 0.85
sinMethod · 0.80
cosMethod · 0.80
appendMethod · 0.45
newMethod · 0.45
DrawMethod · 0.45
lineMethod · 0.45
saveMethod · 0.45

Tested by

no test coverage detected