fractals in python

Solutions on MaxInterview for fractals in python by the best coders in the world

showing results for - "fractals in python"
Camila
29 Feb 2019
1"""
2H-Tree Fractal using recursion and Turtle Graphics.
3Robin Andrews - https://compucademy.net/
4"""
5
6import turtle
7
8SPEED = 5
9BG_COLOR = "blue"
10PEN_COLOR = "lightgreen"
11SCREEN_WIDTH = 800
12SCREEN_HEIGHT = 800
13DRAWING_WIDTH = 700
14DRAWING_HEIGHT = 700
15PEN_WIDTH = 5
16TITLE = "H-Tree Fractal with Python Turtle Graphics"
17FRACTAL_DEPTH = 3
18
19
20def draw_line(tur, pos1, pos2):
21    # print("Drawing from", pos1, "to", pos2)  # Uncomment for tracing the algorithm.
22    tur.penup()
23    tur.goto(pos1[0], pos1[1])
24    tur.pendown()
25    tur.goto(pos2[0], pos2[1])
26
27
28def recursive_draw(tur, x, y, width, height, count):
29    draw_line(
30        tur,
31        [x + width * 0.25, height // 2 + y],
32        [x + width * 0.75, height // 2 + y],
33    )
34    draw_line(
35        tur,
36        [x + width * 0.25, (height * 0.5) // 2 + y],
37        [x + width * 0.25, (height * 1.5) // 2 + y],
38    )
39    draw_line(
40        tur,
41        [x + width * 0.75, (height * 0.5) // 2 + y],
42        [x + width * 0.75, (height * 1.5) // 2 + y],
43    )
44
45    if count <= 0:  # The base case
46        return
47    else:  # The recursive step
48        count -= 1
49        # Top left
50        recursive_draw(tur, x, y, width // 2, height // 2, count)
51        # Top right
52        recursive_draw(tur, x + width // 2, y, width // 2, height // 2, count)
53        # Bottom left
54        recursive_draw(tur, x, y + width // 2, width // 2, height // 2, count)
55        # Bottom right
56        recursive_draw(tur, x + width // 2, y + width // 2, width // 2, height // 2, count)
57
58
59if __name__ == "__main__":
60    # Screen setup
61    screen = turtle.Screen()
62    screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
63    screen.title(TITLE)
64    screen.bgcolor(BG_COLOR)
65
66    # Turtle artist (pen) setup
67    artist = turtle.Turtle()
68    artist.hideturtle()
69    artist.pensize(PEN_WIDTH)
70    artist.color(PEN_COLOR)
71    artist.speed(SPEED)
72
73    # Initial call to recursive draw function
74    recursive_draw(artist, - DRAWING_WIDTH / 2, - DRAWING_HEIGHT / 2, DRAWING_WIDTH, DRAWING_HEIGHT, FRACTAL_DEPTH)
75
76    # Every Python Turtle program needs this (or an equivalent) to work correctly.
77    turtle.done()
78