TheAlgorithms-Python
76 строк · 2.2 Кб
1"""Authors Bastien Capiaux & Mehdi Oudghiri
2
3The Vicsek fractal algorithm is a recursive algorithm that creates a
4pattern known as the Vicsek fractal or the Vicsek square.
5It is based on the concept of self-similarity, where the pattern at each
6level of recursion resembles the overall pattern.
7The algorithm involves dividing a square into 9 equal smaller squares,
8removing the center square, and then repeating this process on the remaining 8 squares.
9This results in a pattern that exhibits self-similarity and has a
10square-shaped outline with smaller squares within it.
11
12Source: https://en.wikipedia.org/wiki/Vicsek_fractal
13"""
14
15import turtle
16
17
18def draw_cross(x: float, y: float, length: float):
19"""
20Draw a cross at the specified position and with the specified length.
21"""
22turtle.up()
23turtle.goto(x - length / 2, y - length / 6)
24turtle.down()
25turtle.seth(0)
26turtle.begin_fill()
27for _ in range(4):
28turtle.fd(length / 3)
29turtle.right(90)
30turtle.fd(length / 3)
31turtle.left(90)
32turtle.fd(length / 3)
33turtle.left(90)
34turtle.end_fill()
35
36
37def draw_fractal_recursive(x: float, y: float, length: float, depth: float):
38"""
39Recursively draw the Vicsek fractal at the specified position, with the
40specified length and depth.
41"""
42if depth == 0:
43draw_cross(x, y, length)
44return
45
46draw_fractal_recursive(x, y, length / 3, depth - 1)
47draw_fractal_recursive(x + length / 3, y, length / 3, depth - 1)
48draw_fractal_recursive(x - length / 3, y, length / 3, depth - 1)
49draw_fractal_recursive(x, y + length / 3, length / 3, depth - 1)
50draw_fractal_recursive(x, y - length / 3, length / 3, depth - 1)
51
52
53def set_color(rgb: str):
54turtle.color(rgb)
55
56
57def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color="blue"):
58"""
59Draw the Vicsek fractal at the specified position, with the specified
60length and depth.
61"""
62turtle.speed(0)
63turtle.hideturtle()
64set_color(color)
65draw_fractal_recursive(x, y, length, depth)
66turtle.Screen().update()
67
68
69def main():
70draw_vicsek_fractal(0, 0, 800, 4)
71
72turtle.done()
73
74
75if __name__ == "__main__":
76main()
77