How to Draw a Fractal Tree with Python and Turtle Graphics

preview_player
Показать описание
This is a Python script that uses the turtle module to draw a fractal tree. The fractal tree is drawn using recursion, where each branch splits into two smaller branches, and each smaller branch splits into two even smaller branches, and so on. The color of the branches changes as the tree is drawn, with the hue gradually increasing.

The script begins by importing the turtle and colorsys modules. It then sets up the turtle window with a specific size and coordinates, and sets the tracer to 0 to prevent the turtle from drawing every time it moves. The turtle is also hidden at the beginning.

The script defines a helper function called set_position_and_move which moves the turtle to a new position and sets its tilt angle. It takes four arguments: the x and y coordinates of the new position, the tilt angle of the turtle, and the length of the segment to draw.

The main function of the script is the fractal_tree function. This function takes five arguments: the starting x and y coordinates of the tree, the length of the first segment to draw, the tilt angle of the turtle, the number of recursive iterations to perform (n), and the initial hue for the color of the segments.

The function first checks if the number of recursive iterations has reached 0, in which case it stops the recursion by returning from the function.

If the recursion is not stopped, the function calculates the RGB color for the current segment using the hsv_to_rgb function from the colorsys module. It then sets the color of the turtle's pen to this color.

The function then calls the set_position_and_move function to move the turtle to the new position and draw the current segment. It then gets the turtle's new position.

The function then recursively calls itself three times: twice with new x and y coordinates and a halved length, and a tilt angle that is shifted 20 degrees to the left and right, respectively. It also decreases n by 1 and increases the hue by 0.03. This creates the left and right branches of the tree. Finally, it calls itself again with the original starting position and a halved length and n decreased by 1, which creates the center branch of the tree. The hue is increased by 0.04 for the center branch.

The script calls the fractal_tree function with specific arguments to draw a fractal tree. It then updates the turtle window and waits for the user to close the window.

Overall, this script demonstrates how recursion can be used to draw complex shapes, such as fractal trees, using the turtle module in Python.

.py link:
Рекомендации по теме
welcome to shbcf.ru