code a fractal tree
- User
code a fractal tree
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
code a fractal tree
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, here's a classic fractal tree implementation using Python's turtle module. This is a great way to visualize recursion.
The core idea is:
import turtle
import random
def draw_fractal_tree(t, length, angle, shrink_factor, min_length, level):
"""
Recursively draws a fractal tree.
Args:
t (turtle.Turtle): The turtle object to draw with.
length (float): The length of the current branch segment.
angle (float): The angle to turn for branching.
shrink_factor (float): Factor by which branch length decreases each level.
min_length (float): The minimum branch length to draw (base case).
level (int): Current recursion depth (optional, useful for coloring/thickness).
"""
if length < min_length:
# Base Case: Draw a 'leaf' and stop recursion for this branch
t.pencolor("green") # Use green for leaves/tips
t.dot(max(3, int(length * 0.8))) # Draw a dot as a leaf
# It's important to return the turtle state if necessary,
# but here we just let the recursion unwind naturally.
# Resetting color for backtracking might be needed depending on logic,
# but backward() handles position/heading restoration below.
return
# --- Draw the current branch ---
# Set pensize based on level or length for thickness variation
current_pensize = max(1, int(length / 10)) # Adjust divisor for desired thickness
t.pensize(current_pensize)
# Optional: Color variation (e.g., brown -> lighter brown -> green)
# Simple approach: Use green for smaller branches
if length < initial_length * 0.3:
t.pencolor("green")
else:
t.pencolor("brown")
t.forward(length)
# Store current position and heading before branching
# This is where the junction point is
current_pos = t.pos()
current_heading = t.heading()
# --- Left Branch ---
t.left(angle)
# Recursive call for the left branch, reducing length and level
draw_fractal_tree(t, length * shrink_factor, angle, shrink_factor, min_length, level - 1)
# --- Right Branch ---
# After the left branch recursion returns, the turtle is back at current_pos
# We need to reposition and re-orient it for the right branch.
# Turtle automatically returns to the state it was in *before* the recursive call,
# but we need to adjust the heading.
# Restore heading to the direction *after* drawing the trunk, before turning left
t.setheading(current_heading)
# Turn right for the right branch
t.right(angle)
# Recursive call for the right branch
draw_fractal_tree(t, length * shrink_factor, angle, shrink_factor, min_length, level - 1)
# --- Return to the start of the current segment ---
# Restore heading to the original direction of this segment
t.setheading(current_heading)
# Move back to the start of this branch segment
t.backward(length)
# --- Screen Setup ---
screen = turtle.Screen()
screen.setup(width=800, height=700)
screen.bgcolor("skyblue")
screen.title("Recursive Fractal Tree")
screen.tracer(0) # Turn off screen updates for much faster drawing
# --- Turtle Setup ---
tree_turtle = turtle.Turtle()
tree_turtle.hideturtle() # Hide the turtle arrow
tree_turtle.speed(0) # Set speed to fastest
tree_turtle.penup()
tree_turtle.goto(0, -250) # Start at the bottom center
tree_turtle.setheading(90) # Point upwards
tree_turtle.pendown()
tree_turtle.color("brown") # Initial color
# --- Parameters ---
initial_length = 120 # Length of the first trunk segment
branch_angle = 25 # Angle between branches
shrink_factor = 0.75 # How much smaller each branch gets (e.g., 0.75 = 75%)
minimum_length = 5 # Stop drawing when branches are shorter than this
initial_level = 10 # Max depth of recursion (can also rely solely on min_length)
# --- Start Drawing ---
draw_fractal_tree(tree_turtle, initial_length, branch_angle, shrink_factor, minimum_length, initial_level)
# --- Finish ---
screen.update() # Update the screen once drawing is complete
screen.mainloop() # Keep the window open until manually closed
How it works:
draw_fractal_tree(t, length, angle, shrink_factor, min_length, level): This is the recursive function.if length < min_length): If the current length is less than the min_length, we consider the branch too small to continue. We change the color to green, draw a small dot (representing a leaf), and return. This stops this path of recursion.t.forward(length)): Draws the current branch segment. Pensize and color are adjusted beforehand.current_pos) and heading (current_heading) right after drawing the segment. This is the "junction point" where branching occurs.angle.draw_fractal_tree again with a reduced length (length * shrink_factor) and decremented level.current_heading (the direction before the left turn).angle.draw_fractal_tree again with the reduced length.setheading(current_heading)).length of the segment it just drew (backward(length)).screen.tracer(0) and screen.update(): These are important for performance. tracer(0) turns off automatic screen updates, and update() forces a single update after all the drawing is done, making the process much faster than updating after every single line segment.screen.mainloop(): Keeps the graphics window open so you can see the result.