| 23 | return state |
| 24 | |
| 25 | def 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 |