import turtleCompiling TURTLE.PAS ... (42 units) CONVERGENCE REPORT import turtle 34/42 (81%) import matplotlib 1/42 import PIL 0/42 ASCII art / other 7/42 RECURSION PATTERNS fractal/recursive tree 38/42 (90%) uses depth parameter 24/42 (57%) TOP RECURSIVE FUNCTION NAMES draw_tree 27 models draw_branch 9 models draw_forest 7 models create_forest 2 models generate_forest 2 models COMMON BRANCH ANGLES angle=90° x28 angle=20° x12 angle=25° x8 angle=40° x5 angle=45° x2 42 units compiled. 0 errors, 0 warnings. Build successful. Press F9 to run.
import turtle
import random
def draw_tree(t, branch_length, angle, depth, shrink_factor):
"""
Recursively draws a tree.
t : turtle object
branch_length : current branch length
angle : branching angle (degrees)
depth : remaining recursion depth
shrink_factor : how much each branch shrinks
"""
if depth == 0:
return
# Set color: darker brown for thicker branches, green for leaves
if depth <= 2:
t.color("green") # leaf tips
else:
t.color("saddle brown") # trunk/branches
# Set pen thickness based on depth (thicker near trunk)
t.pensize(max(1, depth * 0.8))
# Draw the main trunk
t.forward(branch_length)
# Save position and heading for left branch
pos = t.position()
heading = t.heading()
# Left branch
t.left(angle)
draw_tree(t, branch_length * shrink_factor, angle, depth - 1, shrink_factor)
# Restore and go to right branch
t.penup()
t.setposition(pos)
t.setheading(heading)
t.pendown()
# Right branch
t.right(angle)
draw_tree(t, branch_length * shrink_factor, angle, depth - 1, shrink_factor)
# Return to original trunk base (backtrack)
t.penup()
t.setposition(pos)
t.setheading(heading)
t.pendown()
t.backward(branch_length) # go back down
def draw_forest():
"""Draws a forest of recursively generated trees."""
screen = turtle.Screen()
screen.setup(800, 600)
screen.bgcolor("sky blue")
screen.title("Recursive Forest")
t = turtle.Turtle()
t.speed(0) # fastest
t.penup()
t.setheading(90) # point upward
# Draw several trees at random positions
for _ in range(8):
# Random position (avoid edges)
x = random.randint(-350, 350)
y = random.randint(-250, -50) # ground zone
# Random size and shape parameters
tree_height = random.randint(60, 120)
angle = random.randint(15, 35)
depth = random.randint(4, 7)
shrink = random.uniform(0.6, 0.75)
# Move tree to its position
t.penup()
t.goto(x, y)
t.pendown()
t.setheading(90)
# Draw the tree
draw_tree(t, tree_height, angle, depth, shrink)
# Add some ground
t.penup()
t.goto(-400, -250
import turtle
import random
def draw_tree(t, length, depth, max_depth):
"""Recursively draw a fractal tree"""
if depth > max_depth:
return
# Draw the trunk/branch
t.pensize(max(1, (max_depth - depth) * 2)) # Thicker branches lower down
t.pencolor("#3D2312" if depth < 3 else "#6B4423") # Darker trunk at base
t.forward(length)
# Calculate variations
angle_variation = random.randint(-10, 10)
length_variation = random.uniform(0.7, 0.8)
# Draw left branch
t.left(25 + angle_variation)
draw_tree(t, length * length_variation, depth + 1, max_depth)
t.right(25 + angle_variation) # Return to original angle
# Draw right branch
t.right(25 - angle_variation)
draw_tree(t, length * length_variation, depth + 1, max_depth)
t.left(25 - angle_variation) # Return to original angle
# At certain depths, add leaves/needles
if depth == max_depth - 1:
draw_leaves(t, length * 0.5)
# Move back to starting position
t.backward(length)
def draw_leaves(t, size):
"""Draw leaf clusters at branch tips"""
t.fillcolor(random.choice(["#228B22", "#2E8B57", "#32CD32"]))
t.begin_fill()
t.circle(size * 0.3)
t.end_fill()
def draw_forest():
"""Main function
import turtle import random # Set up screen screen = turtle.Screen() screen.bgcolor("skyblue") t = turtle.Turtle() t.speed(0) t.hideturtle() # Recursive tree function def draw_tree(branch_len, t, thickness): if branch_len > 5: t.pensize(thickness) t.forward(branch_len) # Right branch t.right(20) draw_tree(branch_len * 0.7, t, thickness * 0.7) # Left branch t.left(40) draw_tree(branch_len * 0.7, t, thickness * 0.7) # Return to parent t.right(20) t.backward(branch_len) # Draw a single tree def plant_tree(x, y): t.penup() t.goto(x, y) t.pendown() t.setheading(90) draw_tree(random.randint(40, 80), t, 6) # Recursive loop: plant multiple trees def draw_forest(n): if n == 0: return plant_tree(random.randint(-200, 200), random.randint(-150, -50)) draw_forest(n - 1) # Generate the forest draw_forest(8) screen.mainloop()
import turtle
import random
def draw_tree(t, branch_length, angle, depth, thickness):
"""Recursively draw a fractal tree."""
if depth == 0 or branch_length < 2:
# Draw a leaf at the tip
t.color("#2d5016" if random.random() > 0.3 else "#4a7c2e")
t.dot(random.randint(4, 8))
return
# Set branch color (brown gradient based on depth)
brown_shade = max(0, 100 - depth * 10)
t.pencolor((101/255, 67/255, 33/255))
t.pensize(thickness)
# Draw the current branch
t.forward(branch_length)
# Recursive right branch
t.right(angle)
draw_tree(t, branch_length * 0.75, angle, depth - 1, max(1, thickness * 0.7))
# Recursive left branch
t.left(angle * 2)
draw_tree(t, branch_length * 0.75, angle, depth - 1, max(1, thickness * 0.7))
# Sometimes add a middle branch for more variation
if random.random() > 0.5 and depth > 2:
t.right(angle)
draw_tree(t, branch_length * 0.6, angle, depth - 2, max(1, thickness * 0.6))
t.left(angle)
# Return to original position
t.right(angle)
t.backward(branch_length)
def draw_forest(t, x_positions, ground_y):
"""Recursively draw multiple trees to form a forest."""
if not x_positions:
return
# Pick a random tree to draw
x = x_positions[0]
# Move turtle to position without drawing
t.penup()
t.goto(x, ground_y)
t.setheading(90) # Point up
t.pendown()
# Random tree properties
branch_
import turtle
import random
def setup_screen():
"""Setup the drawing canvas"""
screen = turtle.Screen()
screen.setup(800, 600)
screen.bgcolor("skyblue")
screen.title("Recursive Forest")
return screen
def draw_grass():
"""Draw the ground"""
grass = turtle.Turtle()
grass.speed(0)
grass.hideturtle()
grass.penup()
grass.goto(-400, -200)
grass.pendown()
grass.color("darkgreen")
grass.begin_fill()
for _ in range(2):
grass.forward(800)
grass.right(90)
grass.forward(100)
grass.right(90)
grass.end_fill()
def draw_tree(t, branch_length, angle, depth, max_depth):
"""
Recursively draw a tree
Args:
t: turtle object
branch_length: length of current branch
angle: angle between branches
depth: current recursion depth
max_depth: maximum recursion depth
"""
if depth > max_depth or branch_length < 5:
return
# Save current position and heading
position = t.position()
heading = t.heading()
# Draw main branch
t.pensize(max(1, branch_length * 0.1))
t.color("saddlebrown" if depth <= 3 else "forestgreen")
t.forward(branch_length)
# Calculate new branch length
new_length = branch_length * random.uniform(0.6, 0.8)
# Draw right branch
t.right(angle)
draw_tree(t, new_length, angle, depth + 1, max_depth)
# Return to branch point
t.penup()
t.goto(position)
t.setheading(heading + angle)
t.pendown()
t.forward(branch_length)
# Draw left branch
t.left(angle * 2)
draw_tree(t, new_length, angle, depth + 1, max_depth)
# Return to original position and heading
t.penup()
t.goto(position)
t.setheading(heading)
t.pendown()
def draw_pine_tree(t, branch_length, depth, max_depth):
"""
Recursively draw a pine tree with triangular shape
"""
if depth > max_depth or branch_length < 5:
return
# Save position
position = t.position()
heading = t.heading()
# Draw trunk/branch
t.pensize(max(1, branch_length * 0.15))
t.color("brown" if depth <= 2 else "darkgreen")
t.forward(branch_length)
# Draw branches at this level
new_length = branch_length * 0.7
angles = [30, 60, 120, 150] if depth <= 2 else [45, 135]
for angle in angles:
t.penup()
t.goto(position
import turtle
import random
def draw_tree(t, branch_length, angle, depth, pen_size):
"""
Recursively draw a tree.
Args:
t: turtle object
branch_length: length of current branch
angle: branching angle
depth: recursion depth (stops when 0)
pen_size: thickness of branch
"""
if depth == 0 or branch_length < 5:
# Base case: draw leaves
t.color("green")
t.dot(random.randint(4, 8))
return
# Set branch color (brown trunk fading to green)
green_amount = min(1.0, (10 - depth) / 10 + 0.2)
t.color(0.4 - green_amount * 0.2, green_amount * 0.5, 0.0)
t.pensize(max(1, pen_size))
# Draw the current branch
t.forward(branch_length)
# Save current position/heading to return later
pos = t.position()
heading = t.heading()
# Randomize for a natural look
rand_angle = angle + random.randint(-10, 10)
shrink = random.uniform(0.6, 0.75)
# Recurse: right branch
t.right(rand_angle)
draw_tree(t, branch_length * shrink, angle, depth - 1, pen_size - 1)
# Return to branching point
t.penup()
t.setposition(pos)
t.setheading(heading)
t.pendown()
# Recurse: left branch
t.left(rand_angle)
draw_tree(t, branch_length * shrink, angle, depth - 1, pen_size - 1)
# Return to base of this branch
t.penup()
t.setposition(pos)
t.setheading(heading)
t.backward(branch_length)
t.pendown()
def plant_tree(t, x, y, size, depth):
"""Position the turtle and grow a single tree."""
import turtle import random # Setup the screen screen = turtle.Screen() screen.bgcolor("skyblue") screen.title("Recursive Forest") screen.width = 800 screen.height = 600 # Create the turtle t = turtle.Turtle() t.speed(0) # Fastest drawing speed t.hideturtle() # Hide the turtle cursor turtle.tracer(0, 0) # Turns off animation for instant drawing def draw_tree(branch_length, thickness, t): """ Recursively draws a single tree. Base case: When the branch length is less than 5, draw leaves and stop. """ if branch_length < 5: # Base case: Draw a leaf/fruit t.color("forestgreen") t.begin_fill() t.circle(random.randint(3, 6)) t.end_fill() # Backtrack to continue drawing other branches t.backward(branch_length) return # Draw the trunk/branch if thickness > 0: t.pensize(thickness) t.color("saddlebrown" if branch_length > 15 else "olive") t.forward(branch_length) # Recursive step: Right branch angle_right = random.randint(15, 35) t.right(angle_right) draw_tree(branch_length - random.randint(8, 15), thickness * 0.7, t) # Recursive step: Left branch angle_left = random.randint(15, 35) t.left(angle_right + angle_left) draw_tree(branch_length - random.randint(8, 15), thickness * 0.7, t) # Return to the original starting angle and position t.right(angle_left) t.backward(branch_length) def draw_forest(num_trees, t): """Generates a forest by calling the recursive tree function multiple times.""" for _ in range(num_trees): # Pick a random starting position across the screen x = random.randint(-350, 350) y = random.randint(-250, -100) # Pick a random starting size for the tree to give depth to the forest size = random.randint(40, 90) # Move turtle to starting position without drawing t.penup() t.goto(x, y) t.setheading(random.randint(80, 100)) # Point generally upwards t.pendown() # Call the recursive function draw_tree(size, size / 6, t) # Draw the ground after the trees t.penup() t.goto(-400, -260) t.pendown() t.color("darkgreen") t.begin_fill() t.goto(400, -260
import random
def draw_tree(height, width=None, indent=0):
"""Recursively draw a single tree."""
if width is None:
width = height
if height == 0:
# Base case: draw the trunk
trunk = " " * (indent + width // 2) + "║"
print(trunk)
return
# Draw the current level of branches
spaces = " " * (indent + width // 2 - height)
branches = "▲" * (2 * height - 1)
print(f"{spaces}{branches}")
# Recurse to draw the next level
draw_tree(height - 1, width, indent)
def draw_forest(num_trees, max_height=8):
"""Recursively draw a forest of trees."""
if num_trees == 0:
return
# Collect tree data
trees = []
for _ in range(num_trees):
height = random.randint(3, max_height)
trees.append(height)
max_h = max(trees)
forest_lines = []
# Build each tree's lines
all_tree_lines = []
for height in trees:
tree_lines = generate_tree_lines(height, max_h)
all_tree_lines.append(tree_lines)
# Combine trees side by side
for row in range(max_h + 1):
line = ""
for tree_lines in all_tree_lines:
if row < len(tree_lines):
line += tree_lines[row] + " "
else:
line += " " * (max_h * 2) + " "
forest_lines.append(line)
for line in forest_lines:
print(line)
# Recursively add more layers of forest
draw_ground(num_trees, max_h)
def generate_tree_lines(height, max_height):
"""Generate lines for a single tree, padded to max height."""
lines = []
width = max_height * 2
# Add empty lines for alignment
padding = max_height - height
for _ in range(padding):
lines.append(" " * width)
# Draw triangle layers
for level in range(height, 0, -1):
spaces = " " * (height - level)
branches = "▲" * (2 * level - 1)
line = f"{spaces}{branches}"
line = line.ljust(width)
lines.append(line)
# Draw trunk
trunk_pos = height - 1
trunk = " " * trunk_pos + "║"
lines.append(trunk.ljust(width))
return lines
def draw_ground(
import turtle import random # ---------- Setup ---------- screen = turtle.Screen() screen.bgcolor("skyblue") screen.title("Recursive Forest") pen = turtle.Turtle() pen.speed(0) pen.hideturtle() pen.left(90) # ---------- Recursive Tree Function ---------- def draw_tree(length, depth): if depth == 0 or length < 5: # Draw a leaf pen.color(random.choice(["forestgreen", "darkgreen", "limegreen"])) pen.begin_fill() pen.circle(4) pen.end_fill() pen.color("saddlebrown") return # Draw trunk/branch pen.color("saddlebrown") pen.pensize(depth) pen.forward(length) # Left branch angle = random.randint(15, 30) pen.left(angle) draw_tree(length * random.uniform(0.65, 0.8), depth - 1) # Right branch pen.right(angle * 2) draw_tree(length * random.uniform(0.65, 0.8), depth - 1) # Return to original position pen.left(angle) pen.backward(length) # ---------- Draw Ground ---------- pen.penup() pen.goto(-400, -250) pen.pendown() pen.color("darkgreen") pen.begin_fill() pen.goto(400, -250) pen.goto(400, -300) pen.goto(-400, -300) pen.goto(-400, -250) pen.end_fill() # ---------- Draw Forest ---------- for x in range(-350, 351, 100): pen.penup() pen.goto(x + random.randint(-30, 30), -250) pen.setheading(90) pen.pendown() tree_height = random.randint(60, 100) recursion_depth = random.randint(5, 7) draw_tree(tree_height, recursion_depth) # ---------- Finish ---------- turtle.done()
import turtle
import random
def draw_tree(branch_len, t):
"""
Recursive function to draw a single tree.
"""
if branch_len > 5:
# Set thickness based on branch length
t.pensize(branch_len / 10)
# Change color to green for the leaves/small branches
if branch_len < 20:
t.pencolor("forest green")
else:
t.pencolor("saddle brown")
# Draw the branch
t.forward(branch_len)
# Randomize angles and length to make trees look natural
angle = random.randint(15, 30)
reduction = random.uniform(10, 15)
# Right recursion
t.right(angle)
draw_tree(branch_len - reduction, t)
# Left recursion
t.left(angle * 2)
draw_tree(branch_len - reduction, t)
# Return to the previous node
t.right(angle)
t.penup()
t.backward(branch_len)
t.pendown()
def create_forest(num_trees):
screen = turtle.Screen()
screen.bgcolor("skyblue")
t = turtle.Turtle()
t.speed(0) # Fastest setting
t.left(90) # Face upwards
# Hide turtle and lift pen for setup
t.hideturtle()
for _ in range(num_trees):
# Pick a random spot for the tree base
x = random.randint(-300, 300)
y = random.randint(-250, -50)
t.penup()
t.goto(x, y)
t.pendown()
# Draw a tree with a random starting height
draw_tree(random.randint(40, 70), t)
screen.exitonclick()
# Generate a forest with 10 recursive trees
create_forest(10)
import random
def draw_forest(width, height, density=0.3):
"""
Generate a forest ASCII art using recursion.
Args:
width: Width of the forest area
height: Height of the forest area
density: Probability of a tree appearing (0.0 to 1.0)
Returns:
ASCII forest as a string
"""
# Base case: empty forest area
if width <= 0 or height <= 0:
return ""
# Helper function to draw a single tree recursively
def draw_tree(height, trunk_height=2):
if height <= 0:
return ""
if height == 1:
# Tree top (star or leaf)
return ["*"]
elif height > trunk_height:
# Draw canopy layers
tree_layers = draw_tree(height-1, trunk_height)
current_width = (height - trunk_height) * 2 - 1
spaces = (max_width - current_width) // 2
layer = " " * spaces + "/" + "▲" * (current_width - 2) + "\\"
return [layer] + tree_layers
else:
# Draw trunk
tree_layers = draw_tree(height-1, trunk_height)
spaces = (max_width - 1) // 2
layer = " " * spaces + "|"
return [layer] + tree_layers
# Helper function to place trees in the forest
def place_tree(x, y, tree_height, forest_grid):
"""
Recursively place a tree in the forest grid
"""
# Base case: tree fully drawn
if tree_height <= 0:
return
if tree_height > trunk_height:
# Draw canopy
width_at_level = (tree_height - trunk_height) * 2 - 1
if 0 <= y - tree_height + trunk_height < height:
start_x = x - width_at_level // 2
for i in range(width_at_level):
current_x = start_x + i
if 0 <= current_x < width:
if forest_grid[y - tree_height + trunk_height][current_x] == " ":
forest_grid[y - tree_height + trunk_height][current_x] = "▲"
# Recursively draw next level
place_tree(x, y, tree_height-1, forest_grid)
else:
# Draw trunk
for level in range(trunk_height):
current_y = y - level
if 0 <= current_y < height and 0 <= x < width:
forest_grid[current_y][x] = "|"
# Create forest grid
max_width = min(width, 20) # Limit tree width
forest_grid = [[" " for _ in range(width)] for _ in range(height)]
# Define trunk height
trunk_height = random.randint(1, 3)
# Place trees using probability density
def populate_forest(y):
if y >= height:
return
def place_at_level(x
import turtle import random # --- Recursive Tree Drawing Function --- def draw_tree(t, branch_length, angle, depth, pen_size): """ Recursively draws a tree. Args: t (turtle.Turtle): The turtle object for drawing. branch_length (float): The length of the current branch. angle (float): The angle to turn for branches. depth (int): The recursion depth (controls tree complexity). pen_size (float): The width of the pen for drawing branches. """ if depth == 0: return # Set pen size for thicker branches at the base t.pensize(max(1, pen_size)) # Draw the current branch t.forward(branch_length) # Store current position and
import turtle import random # --- CONFIGURATION --- SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 700 NUM_TREES = 8 # How many trees in the forest INITIAL_BRANCH_LEN = 80 # Base size of trees MIN_BRANCH_LEN = 5 # Recursion base case for branches BRANCH_ANGLE = 25 # Angle of split SHRINK_FACTOR = 0.65 # How much smaller branches get TRUNK_WIDTH = 10 # Starting pen width def setup_screen(): """Initialize the turtle screen.""" screen = turtle.Screen() screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT) screen.title("Recursive Forest Generator") screen.bgcolor("#1a1a2e") # Dark night blue screen.tracer(0, 0) # Turn off animation for instant drawing return screen def setup_turtle(): """Configure the drawing pen.""" t = turtle.Turtle() t.hideturtle() t.speed(0) # Fastest t.left(90) # Point up t.penup() return t # ========================================== # LEVEL 1 RECURSION: The Fractal Branches # ========================================== def draw_branch(t, length, width): """ Recursively draws a single tree structure. Base Case: Length is too small. Recursive Step: Draw trunk -> Turn -> Draw Left Branch -> Turn -> Draw Right Branch -> Return. """ if length < MIN_BR
import turtle
import random
import math
def draw_branch(t, branch_length, level):
"""
Recursively draws a branch of a tree.
Args:
t (turtle.Turtle): The turtle object.
branch_length (float): The current length of the branch.
level (int): The current recursion depth (determines color, thickness).
"""
if branch_length < 5: # Base case: branch is too small to draw further
return
# Adjust color based on level (becomes greener/browner)
t.pencolor(0.2 + level * 0.05, 0.4 + level * 0.05, 0.1) # Greenish-brown
t.pensize(2 + level * 0.5) # Thicker branches for lower levels
# Draw the current branch segment
t.forward(branch_length)
# Recursive calls for smaller branches
# Each sub-branch is shorter and at a different angle
angle1 = random.uniform(20, 35)
angle2 = random.uniform(20, 35)
reduction_factor = random.uniform(0.6, 0.8)
# Branch 1 (right)
t.right(angle1)
draw_branch(t, branch_length * reduction_factor, level + 1)
t.left(angle1) # Return to original heading
# Branch 2 (left)
t.left(angle2)
draw_branch(t, branch_length * reduction_factor, level + 1)
t.right(angle2) # Return to original heading
# Optional: A third, smaller branch sometimes
if random.random() < 0.3: # 30% chance of a third branch straight ahead
t.right(random.uniform(-10, 10)) # Slight deviation
draw_branch(t, branch_length * reduction_factor * 0.7, level + 1)
t.left(random.uniform(-10, 10))
# Go back to the starting point of this branch segment
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Recursive Forest – draws a forest of fractal trees using turtle graphics. Run: python forest.py """ import turtle import random import sys # ---------------------------------------------------------------------- # Configuration --------------------------------------------------------- # ---------------------------------------------------------------------- # You can play with these values to get different looks. # Number of trees in the forest (more → slower) TREE_COUNT = 30 # Minimal branch length – recursion stops when a branch gets this short. MIN_BRANCH = 5 # Branch length reduction factor (0 < factor < 1). Smaller → deeper trees. LENGTH_FACTOR = 0.75 # Maximum turning angle for each split (degrees) MAX_ANGLE = 30 # Height of the ground line (as a fraction of the screen height) GROUND_LEVEL = -0.4 # Colour palettes – you can add or replace any you like TRUNK_COLORS = ["sienna", "peru", "saddlebrown", "brown"] LEAF_COLORS = ["forestgreen", "limegreen", "olive", "darkgreen", "seagreen"] # ---------------------------------------------------------------------- # Helper functions ------------------------------------------------------ # ---------------------------------------------------------------------- def set_random_color(pen, kind="leaf"): """Pick a colour from the appropriate palette.""" if kind == "trunk": pen.pencolor(random.choice(TRUNK_COLORS)) pen.fillcolor(pen.pencolor()) else: pen.pencolor(random.choice(LEAF_COLORS)) pen.fillcolor(pen.pencolor()) # ---------------------------------------------------------------------- # Recursive drawing routine --------------------------------
import turtle
import random
def draw_branch(branch_length, pen_size, t):
"""
Recursively draws a tree branch with smaller sub-branches.
"""
if branch_length > 5: # Base case: stop when branches get too small
# Draw the current branch
t.pensize(pen_size)
t.forward(branch_length)
# Random angle variation for natural look
angle = random.randint(15, 30)
shrink = random.uniform(0.65, 0.8)
# Right subtree - recursive call
t.right(angle)
draw_branch(branch_length * shrink, pen_size * 0.7, t)
# Left subtree - recursive call
t.left(angle * 2)
draw_branch(branch_length * shrink, pen_size * 0.7, t)
# Return to original position and orientation
t.right(angle)
t.backward(branch_length)
def draw_tree(x, y, trunk_length, t):
"""
Draws a complete tree at position (x, y).
"""
t.penup()
t.goto(x, y)
t.setheading(90) # Point upward
t.pendown()
t.color("saddle brown")
draw_branch(trunk_length, trunk_length / 10, t)
# Draw leaves at the end using a simple recursive leaf cluster
t.color("forest green")
draw_leaves(x, y + trunk_length * 0.8, 3, t)
def draw_leaves(x, y, size, t):
"""
Recursively draws leaf clusters.
"""
if size < 0.5:
return
t.penup()
t.goto(x + random.randint(-20, 20), y + random.randint(-10, 10))
t.pendown()
# Draw a leaf (small circle)
t.begin_fill()
t.circle(size * 3)
t.end_fill()
# Recursive leaf clusters
if size > 1:
for _ in range(3):
new_x = x + random.randint(-15, 15)
new_y = y + random.randint(5, 20)
draw_leaves(new_x, new_y, size * 0.6, t)
def draw_ground(t):
"""
Draws the forest ground.
"""
t.penup()
t.goto(-400, -200)
t.pendown()
t.color("dark green")
t.begin_fill()
for _ in range(2):
t.forward(800)
t.left(90)
t.forward(100)
t.left(90)
t.end_fill()
def draw_sky(t):
"""
Draws sky with recursive clouds.
"""
t.penup()
t.goto(-400, 200)
t.pendown()
t.color("light blue")
t.begin_fill()
for _ in range(2):
t.forward(800)
t.right(90)
t.forward(400)
t.right(
import turtle
def draw_tree(branch_length, t):
if branch_length > 5:
t.forward(branch_length)
t.right(20)
draw_tree(branch_length - 15, t)
t.left(40)
draw_tree(branch_length - 15, t)
t.right(20)
t.backward(branch_length)
def generate_forest():
screen = turtle.Screen()
screen.bgcolor("skyblue")
t = turtle.Turtle()
t.speed(0)
t.left(90)
t.penup()
t.goto(-200, -100)
t.pendown()
t.color("brown")
# Draw multiple trees with different positions and sizes
for x in [-200, -100, 0, 100, 200]:
t.penup()
t.goto(x, -100)
t.pendown()
t.setheading(90)
draw_tree(80, t)
screen.exitonclick()
generate_forest()
import turtle import random screen = turtle.Screen() screen.bgcolor("skyblue") # Set background to sky blue screen.title("Recursive Forest Generator") pen = turtle.Turtle() pen.speed(0) # Fastest drawing speed pen.hideturtle() def draw_tree(branch_len, t): """ Recursive function to draw a tree structure. 1. Draw a trunk. 2. Branch left and right. 3. Call itself with smaller branches until length is too short. """ if branch_len > 5: # Base case: stop recursion when branches get tiny # Draw the current branch/trunk t.forward(branch_len) # Right sub-branch t.right(20) draw_tree(branch_len - 15, t) # Left sub-branch t.left(40) draw_tree(branch_len - 15, t) # Return to original position and angle to complete the recursion step t.right(20) t.backward(branch_len) else: # When branches are small enough, draw green "leaves" t.color("forestgreen") t.circle(3) # Small dot for leaves t.color("brown") def draw_forest(x, y, count): """ Recursive function to place trees across the scene. """ if count > 0: # Move to position pen.penup() # Randomize x slightly to avoid straight lines, # but move generally left to right start_x = -200 + (count * 10) + random.randint(-50, 50) start_y = -150 + random.randint(-20, 20) # Ground level variation pen.goto(start_x, start_y) pen.pendown() pen.left(90) # Face up # Vary tree size for depth initial_len = 60 + random.randint(0, 40) # Call the tree-drawing recursion draw_tree(initial_len, pen) pen.setheading(0) # Reset angle # RECURSIVE CALL: Draw the next tree draw_forest(-200, -150, count - 1) # --- Start the Drawing --- # Draw 10 trees using the spatial recursion draw_forest(-200, -150, 10) # Keep window open screen.mainloop()
import turtle import random # Set up the turtle screen screen = turtle.Screen() screen.bgcolor("skyblue") screen.title("Recursive Forest") # Create the main turtle for drawing t = turtle.Turtle() t.speed(0) # Fastest drawing speed t.hideturtle() # Create a separate turtle just for drawing the ground ground_turtle = turtle.Turtle() ground_turtle.speed(0) ground_turtle.hideturtle() ground_turtle.color("forestgreen") ground_turtle.penup() ground_turtle.goto(-400, -150) ground_turtle.pendown() ground_turtle.begin_fill() ground_turtle.forward(800) ground_turtle.right(90) ground_turtle.forward(300) ground_turtle.right(90) ground_turtle.forward(800) ground_turtle.right(90) ground_turtle.forward(300) ground_turtle.end_fill() def draw_tree(branch_length, depth): """ RECURSIVE LOOP 1: Draws a single fractal tree. - branch_length: how long the current branch is - depth: how many levels of branching are left """ # Base Case: When depth reaches 0, draw a leaf (green dot) and stop branching. if depth == 0: t.color("forestgreen") t.dot(8) # Draws a small circle for a leaf return # Recursive Step: Draw the current branch, then split into smaller branches. # Determine color and thickness based on depth (trunk vs. branches) if depth > 3: t.color("saddlebrown") t.width(depth * 1.5) else: t.color("olive") t.width(depth) # Draw the branch forward t.forward(branch_length) # Add some organic randomness to angles and shrink factor angle_left = random.randint(15, 35) angle_right = random.randint(15, 35) shrink_factor = random.uniform(0.6, 0.75) # Turn left and recursively draw the left sub-tree t.left(angle_left) draw_tree(branch_length * shrink_factor, depth - 1) # Turn right and recursively draw the right sub-tree t.right(angle_left + angle_right) # Net right turn draw_tree(branch_length * shrink_factor, depth - 1) # Turn back to the original heading and backtrack to the start of this branch t.left(angle_right) t.color("saddlebrown" if depth > 3 else "olive") t.width(depth * 1.5 if depth > 3 else depth) t.backward(branch_length) def generate_forest(num_trees, x_pos
import turtle
def draw_tree(branch_length, t):
if branch_length > 5:
# Draw the main branch
t.forward(branch_length)
# Draw the right subtree
t.right(20)
draw_tree(branch_length - 15, t)
# Draw the left subtree
t.left(40)
draw_tree(branch_length - 15, t)
# Backtrack to the main branch
t.right(20)
t.backward(branch_length)
def draw_forest():
screen = turtle.Screen()
screen.bgcolor("skyblue") # Set background color for the forest
t = turtle.Turtle()
t.color("brown")
t.speed(0) # Fastest drawing speed
t.left(90) # Point the turtle upwards
t.penup()
t.backward(100) # Move turtle down to start
t.pendown()
t.forward(100) # Move back up to position
draw_tree(80, t) # Draw first tree
# Draw multiple trees at different positions
for x in range(-200, 200, 100):
for y in range(-200, 200, 100):
t.penup()
t.goto(x, y)
t.pendown()
draw_tree(80, t)
t.hideturtle()
turtle.done()
draw_forest()
To generate a picture of a forest using recursion in Python, the best tool is the built-in `turtle` graphics library.
import turtle
import random
def draw_tree(t, branch_length, level):
if level == 0:
return
# Draw the branch
t.forward(branch_length)
# Save current state
angle = random.randint(15, 35)
shrink = random.uniform(0.6, 0.8)
# Right branch
t.right(angle)
draw_tree(t, branch_length * shrink, level - 1)
# Left branch
t.left(2 * angle)
draw_tree(t, branch_length * shrink, level - 1)
# Return to original position and heading
t.right(angle)
t.backward(branch_length)
def draw_forest():
screen = turtle.Screen()
screen.bgcolor("lightblue")
t = turtle.Turtle()
t.speed(0)
t.hideturtle()
t.left(90)
# Draw multiple trees at different positions
for x in [-250, -100, 50, 200]:
t.penup()
t.goto(x, -250)
t.setheading(90)
t.pendown()
t.color("brown")
draw_tree(t, random.randint(60, 100), 6)
screen.mainloop()
draw_forest()
import turtle
import random
def draw_branch(t, branch_length):
"""
Recursive function to draw a tree branch.
"""
if branch_length > 5:
# Draw the main branch
t.forward(branch_length)
# Determine angle and size for the next branches
angle = random.randint(15, 30)
sub_branch = branch_length * random.uniform(0.6, 0.8)
# Draw right subtree
t.right(angle)
draw_branch(t, sub_branch)
# Draw left subtree
t.left(angle * 2)
draw_branch(t, sub_branch)
# Return to main trunk
t.right(angle)
t.penup()
t.backward(branch_length)
t.pendown()
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("skyblue")
# Set up the turtle
pen = turtle.Turtle()
pen.speed(0) # Fastest speed
pen.left(90) # Point upwards
# Generate a forest
positions = [-300, -150, 0, 150, 300]
for x in positions:
pen.penup()
pen.goto(x, -250)
pen.pendown()
pen.color("brown")
draw_branch(pen, random.randint(80, 120))
turtle.done()
#!/usr/bin/env python3 """ Recursive forest drawer – pure Python + turtle. Run: python3 forest.py Close the turtle window when you are done viewing the picture. """ import turtle import random import math # ------------------------------------------------------------ # Configuration – tweak these to change the look of the forest # ------------------------------------------------------------ SCREEN_WIDTH = 900 SCREEN_HEIGHT = 600 NUM_TREES = 12 # how many trees to plant TRUNK_LENGTH = 80 # length of the first trunk segment MIN_BRANCH = 5 # stop recursion when a branch gets this short ANGLE_VARIANCE = 15 # degrees of random spread for each split LENGTH_FACTOR = 0.7 # each child branch is this fraction of its parent TRUNK_COLOR = ("saddle brown", "sienna") LEAF_COLOR = ("forest green", "dark green") BACKGROUND = "light sky blue" # ------------------------------------------------------------ # Recursive tree drawing # ------------------------------------------------------------ def draw_branch(t: turtle.Turtle, length: float, depth: int): """ Recursively draw a single branch (and its sub‑branches). Parameters ---------- t : turtle.Turtle – the drawing pen length : float – length of the current branch depth : int – recursion depth (used only for colour/width) """ if length < MIN_BRANCH: # draw a little leaf tuft at the tip t.color(*LEAF_COLOR) t.dot(length * 2) # a simple circular leaf t.color(*TRUNK_COLOR) return # Set pen width – thicker near the trunk, thinner toward the tips t.width(max(1, int(depth / 3 + 1))) # Draw the main segment t.forward(length) # Save current state so we can return to it after drawing each side‑branch pos = t.position() heading = t.heading() # ----- left sub‑branch ----- t.left(random.uniform(20, 40) + ANGLE_VARIANCE) draw_branch(t, length * LENGTH_FA
import random
import time
def draw_tree(depth, width):
"""
A recursive function to draw a single tree.
depth: how many levels of branches to draw
width: the base width of the tree
"""
if depth == 0:
return ""
# The trunk (only at the base level or if we want small branches)
trunk = " " * (width // 2) + "|"
# The leaves (the recursive part)
# We create layers of leaves by calling the function with less depth
leaf_layer = ""
padding = " " * (width // 2)
# Generate the triangular canopy
canopy = ""
for i in range(depth):
spaces = " " * (depth - i - 1)
leaves = "*" * (2 * i + 1)
canopy += spaces + leaves + "\n"
return canopy + trunk + "\n"
def generate_forest(rows, cols):
"""
Generates a forest by placing trees at random intervals.
"""
# Initialize an empty grid (list of lists)
forest = [[" " for _ in range(cols)] for _ in range(rows)]
def place_tree_recursive(current_row, current_col):
# Base Case: If we exceed the grid boundaries
if current_row >= rows:
return
# Decide whether to plant a tree at this coordinate (random chance)
if random.random() > 0.8:
# Determine tree height based on row (taller trees at the bottom)
tree_height = random.randint(2, 4)
# Draw the tree into the grid
# (Simple implementation: just placing a 'tree' symbol for speed)
# In a real fractal, this would be more complex.
forest[current_row][current_col] = "♣"
if current_row > 0:
forest[current_row-1][current_col] = "▲"
if current_row > 1:
forest[current_row-2][current_col] = "▲"
# Recursive Step: Move to the next cell (Right or Down)
# This simulates a "scan" through the forest floor
next_col = current_col + 1
next_row = current_row
if next_col >= cols:
next_col = 0
next_row = current_row + 1
place_tree_recursive(next_row, next_col)
# Start recursion from 0,0
# Note: For very large forests, Python's recursion limit would be hit.
#
import turtle
import random
def draw_branch(t, branch_length, thickness, depth, max_depth):
"""Recursively draw a tree branch that splits into smaller branches."""
if depth > max_depth or branch_length < 5:
# Base case: draw a leaf
draw_leaf(t, depth)
return
# Draw the current branch
t.pensize(thickness)
t.pencolor(branch_color(depth, max_depth))
t.forward(branch_length)
# Save current state
current_pos = t.position()
current_heading = t.heading()
# --- Right branch ---
right_angle = random.randint(15, 40)
right_length = branch_length * random.uniform(0.6, 0.8)
right_thickness = thickness * 0.7
t.right(right_angle)
draw_branch(t, right_length, right_thickness, depth + 1, max_depth)
# Restore state
t.penup()
t.goto(current_pos)
t.setheading(current_heading)
t.pendown()
# --- Left branch ---
left_angle = random.randint(15, 40)
left_length = branch_length * random.uniform(0.6, 0.8)
left_thickness = thickness * 0.7
t.left(left_angle)
draw_branch(t, left_length, left_thickness, depth + 1, max_depth)
# Restore state
t.penup()
t.goto(current_pos)
t.setheading(current_heading)
t.pendown()
# --- Optional middle branch (adds fullness) ---
if random.random() > 0.4 and depth < max_depth - 1:
mid_angle = random.randint(-10, 10)
mid_length = branch_length * random.uniform(0.5, 0.7)
mid_thickness = thickness * 0.6
t.left(mid_angle)
draw_branch(t, mid_length, mid_thickness, depth + 1, max_depth)
t.penup()
t.goto(current_pos)
t.setheading(current_heading)
t.pendown()
def draw_leaf(t, depth):
"""Draw a small leaf at the end of a branch."""
leaf_colors = ["#228B22", "#32CD32", "#006400", "#2E8B57", "#3CB371", "#66BB6A"]
t.pencolor(random.choice(leaf_colors))
t.fillcolor(random.choice(leaf_colors))
import random
def draw_tree(height, indent=0, seed=None):
"""
Recursively draw a tree with branches
Args:
height: Height of the tree (recursion depth)
indent: Current indentation level
seed: Random seed for reproducibility
"""
if seed is not None:
random.seed(seed)
if height == 0:
return
# Draw the current level of the tree
spaces = " " * indent
width = height * 2
if height == 1:
print(spaces + "🌲") # Leaf emoji
else:
# Draw branches
print(spaces + "*" * width)
# Recursive calls for left and right branches
draw_tree(height - 1, indent + 2, None)
print(spaces + " " * (width // 2) + "|") # Trunk
draw_tree(height - 1, indent + 2, None)
def draw_forest(num_trees, max_height=5):
"""Draw multiple trees side by side"""
print("\n🌲🌲🌲 FOREST 🌲🌲🌲\n")
for i in range(num_trees):
draw_tree(max_height, seed=i)
print()
# Run the forest generator
draw_forest(num_trees=3, max_height=4)
import turtle
def draw_tree(branch_length):
if branch_length > 5:
# Draw the trunk
turtle.forward(branch_length)
# Draw the branches
draw_tree(branch_length - 15)
turtle.left(45)
draw_tree(branch_length - 15)
turtle.right(90)
draw_tree(branch_length - 15)
turtle.left(45)
turtle.backward(branch_length)
# Set up the screen and turtle
screen = turtle.Screen()
screen.bgcolor("white")
t = turtle.Turtle()
t.speed(0)
# Draw the forest
t.left(90)
t.up()
t.backward(200)
t.down()
t.color("green")
draw_tree(100)
# Hide the turtle and close the window on click
t.hideturtle()
turtle.done()
To generate a picture of a forest using a recursive loop, Python's built-in Turtle graphics library is the
import turtle
import random
def draw_tree(branch_len, t):
"""
Recursive function to draw a fractal tree.
"""
if branch_len > 5: # Base case: stop when branches are too short
# Draw the main branch
t.forward(branch_len)
# Right subtree
t.right(25 + random.randint(-10, 10)) # Randomize angle for natural look
draw_tree(branch_len - 15, t)
# Left subtree
t.left(50 + random.randint(-10, 10))
draw_tree(branch_len - 15, t)
# Return to the original position/angle
t.right(25 + random.randint(-10, 10))
t.backward(branch_len)
def create_forest():
# Setup the screen
screen = turtle.Screen()
screen.bgcolor("skyblue")
# Setup the turtle
t = turtle.Turtle()
t.speed(0) # Fastest speed
t.left(90) # Point upwards
t.up() # Lift pen to move without drawing
# Loop to plant multiple trees
for _ in range(6):
# Move to a random position on the "ground"
x = random.randint(-300, 300)
y = random.randint(-200, -100)
t.goto(x, y)
t.down()
# Set color to brown for trunk, green for leaves
t.pencolor("brown")
# Randomize the size of each tree
tree_size = random.randint(40, 80)
draw_tree(tree_size, t)
t.up()
# Finish
t.hideturtle()
print("Forest generated! Click the window to close.")
screen.exitonclick()
if name == "main":
create_forest()
import turtle import random screen = turtle.Screen() screen.bgcolor("skyblue") pen = turtle.Turtle() pen.hideturtle() pen.speed(0) pen.left(90) pen.up() pen.goto(0, -250) pen.down() def draw_branch(t, length, thickness): if length < 10: return t.pensize(thickness) t.pencolor("sienna") t.forward(length) # Save position and heading pos = t.position() heading = t.heading() # Left branch t.left(random.randint(15, 30)) draw_branch(t, length * random.uniform(0.65, 0.8), thickness * 0.75) # Restore t.up() t.goto(pos) t.setheading(heading) t.down() # Right branch t.right(random.randint(15, 30)) draw_branch(t, length * random.uniform(0.65, 0.8), thickness * 0.75) # Restore again t.up() t.goto(pos) t.setheading(heading) t.down() # Draw leaves at the ends if length < 30: t.dot(random.randint(6, 12), "darkgreen") def draw_tree(x, y, trunk_length): pen.up() pen.goto(x, y) pen.setheading(90) pen.down() draw_branch(pen, trunk_length, trunk_length / 10) # Draw multiple trees for x in range(-350, 351, 70): height = random.randint(60, 120) draw_tree(x, -250, height) turtle.done()
import turtle import random # Setup the screen screen = turtle.Screen() screen.bgcolor("skyblue") # The sky screen.title("Recursive Forest") # Create the turtle artist = turtle.Turtle() artist.speed(0) # Fastest drawing speed artist.hideturtle() # --- Recursive Function --- def draw_tree(branch_length, pen): """ Recursively draws a single tree. """ if branch_length > 5: # 1. Draw the trunk/branch pen.forward(branch_length) # 2. Recursive step: Draw right branch pen.right(20) draw_tree(branch_length - 15, pen) # 3. Recursive step: Draw left branch pen.left(40) draw_tree(branch_length - 15, pen) # 4. Return to original position pen.right(20) pen.backward(branch_length) # --- Main Loop to Generate Forest --- def generate_forest(num_trees): """ Loops to place multiple trees. """ for _ in range(num_trees): # Pick a random spot on the ground x = random.randint(-300, 300) y = random.randint(-200, -50) # Pick a random size for the tree size = random.randint(40, 100) # Move to the spot without drawing artist.penup() artist.goto(x, y) artist.pendown() # Set color: Brown trunk, Green leaves # We draw a small brown trunk first artist.color("brown") artist.setheading(90) # Point up # Draw the tree recursively # We swap colors halfway through recursion to simulate leaves if size > 50: artist.color("brown") else: artist.color("darkgreen") draw_tree(size, artist) # Run the generation generate_forest(10) # Draws 10 trees # Keep the window open screen.mainloop()
import turtle
def draw_branch(t, branch_length, pen_size):
"""
Recursive function to draw a branch.
t: the turtle object
branch_length: the current length of the branch
pen_size: the thickness of the branch
"""
if branch_length > 5:
# Draw the branch
t.pensize(pen_size)
t.forward(branch_length)
# Right sub-branch
t.right(25)
draw_branch(t, branch_length * 0.7, pen_size * 0.7)
# Left sub-branch
t.left(50)
draw_branch(t, branch_length * 0.7, pen_size * 0.7)
# Return to main trunk
t.right(25)
t.backward(branch_length)
# Setup screen and turtle
screen = turtle.Screen()
screen.bgcolor("skyblue")
pen = turtle.Turtle()
pen.speed(0) # Fastest speed
pen.left(90) # Point upwards
pen.up()
pen.goto(0, -250)
pen.down()
pen.color("brown")
# Start the recursion
draw_branch(pen, 100, 10)
turtle.done()
import turtle
import random
def draw_tree(branch_len, t):
"""
Recursive function to draw a fractal tree.
Base case: branch_len <= 5 (stops recursion)
Recursive step: draws a branch, splits into two smaller branches, and returns.
"""
if branch_len > 5:
# Color transition: brown for trunk/wood, green for leaves
if branch_len <= 15:
t.color("forestgreen")
else:
t.color("saddlebrown")
# Thickness transition: branches get thinner as they grow
t.pensize(max(1, branch_len / 10))
# Draw the current branch
t.forward(branch_len)
# Randomize angles and branch reduction for a natural, organic look
right_angle = random.uniform(15, 35)
left_angle = random.uniform(15, 35)
reduction = random.uniform(8, 12)
# --- RIGHT BRANCH (Recursive Call 1) ---
t.right(right_angle)
draw_tree(branch_len - reduction, t)
# --- LEFT BRANCH (Recursive Call 2) ---
# We turn left by (right_angle + left_angle) to cross over to the left side
t.left(right_angle + left_angle)
draw_tree(branch_len - reduction, t)
# --- RETURN TO TRUNK ---
# Turn right by left_angle to face the exact original direction, then step back
t.right(left_angle)
t.backward(branch_len)
def generate_forest():
# 1. Setup the Canvas
screen = turtle.Screen()
screen.title("Recursive Python Forest")
screen.bgcolor("skyblue")
screen.setup(width=1000, height=800)
t = turtle.Turtle()
t.hideturtle()
# Instant drawing (Crucial for recursive fractals so the window doesn't freeze)
screen.tracer(0)
# 2. Draw the Ground
t.penup()
t.goto(-600, -250)
t.pendown()
t.color("darkgreen")
t.begin_fill()
for _ in range(2):
t.forward(1200)
t.right(90)
t.forward(300)
t.right(90)
t.end_fill()
# 3. Plant the Forest (Loop to create multiple recursive trees)
num_trees = 15
for _ in range
import matplotlib.pyplot as plt
import numpy as np
import random
def draw_branch(ax, x, y, length, angle, depth, max_depth, colors):
"""
Recursive function to draw a fractal tree branch.
"""
# Base Case: Stop recursion if depth reaches 0 or branch is too short
if depth == 0 or length < 0.5:
return
# Calculate the end coordinates of the current branch
x_end = x + length * np.cos(angle)
y_end = y + length * np.sin(angle)
# Determine line width based on depth (thicker at the trunk, thinner at leaves)
lw = (depth / max_depth) * 8 + 0.5
# Draw the branch
ax.plot([x, x_end], [y, y_end], color=colors['trunk'], lw=lw, solid_capstyle='round')
# If we are at the tips of the branches, draw leaf clusters
if depth <= 2:
leaf_size = (max_depth - depth) * 15
ax.scatter(x_end, y_end, s=leaf_size, c=[colors['leaves']], alpha=0.6, edgecolors='none')
# Randomize branch characteristics for a natural, organic look
length_factor = random.uniform(0.65, 0.80)
angle_spread_left = random.uniform(0.25, 0.55)
angle_spread_right = random.uniform(0.25, 0.55)
# Slight wind effect
wind = random.uniform(-0.05, 0.1)
# Recursive Step: Draw left and right sub-branches
draw_branch(ax, x_end, y_end, length * length_factor, angle + angle_spread_left + wind, depth - 1, max_depth, colors)
draw_branch(ax, x_end, y_end, length * length_factor, angle - angle_spread_right + wind, depth - 1, max_depth, colors)
# Occasionally draw a middle branch for fuller trees
if random.random() > 0.6:
draw_branch(ax, x_end, y_end, length * length_factor * 0.8, angle + wind, depth - 1, max_depth, colors)
def generate_forest(num_trees=25, seed=None):
"""
Sets up the canvas and generates a forest using
import turtle
import random
def draw_tree(t, branch_len, angle, shrink_factor, min_len):
"""
Recursively draws a tree with branches.
"""
if branch_len < min_len:
# Draw leaves at the end of small branches
t.color('green')
t.dot(random.randint(4, 8))
t.color('saddlebrown')
return
# Draw the current branch
t.pensize(max(1, branch_len / 10))
t.forward(branch_len)
# Right subtree
t.right(angle)
draw_tree(t, branch_len * shrink_factor, angle, shrink_factor, min_len)
# Left subtree (plus a middle branch for fuller trees)
t.left(angle * 2)
draw_tree(t, branch_len * shrink_factor, angle, shrink_factor, min_len)
# Optional middle branch for denser forest
if branch_len > min_len * 3 and random.random() > 0.5:
t.left(angle)
draw_tree(t, branch_len * shrink_factor * 0.8, angle, shrink_factor, min_len)
t.right(angle)
else:
t.right(angle)
# Return to start of this branch
t.right(angle)
t.backward(branch_len)
def draw_ground(t, width, height):
"""Draws the ground/horizon."""
t.penup()
t.goto(-width/2, -height/3)
t.pendown()
t.color('forestgreen')
t.begin_fill()
for _ in range(2):
t.forward(width)
t.left(90)
t.forward(height/3)
t.left(90)
t.end_fill()
def draw_sun(t, x, y, radius):
"""Draws a sun/moon."""
t.penup()
t.goto(x, y)
t.pendown()
t.color('gold')
t.begin_fill()
t.circle(radius)
t.end_fill()
def draw_forest_recursive(t, num_trees, x_start, x_end, y_base, min_size, max_size, depth=0):
"""
Recursively places trees across the landscape.
"""
if num_trees <= 0 or depth > 10:
return
# Calculate position for this tree
x_pos = random.uniform(x_start, x_end)
# Size varies by position (perspective: smaller further away)
distance_factor = (x_pos - x_start) / (x_end - x_start)
base_size = random.uniform(min_size, max_size)
size = base_size * (0.7 + 0.6 * abs(distance_factor - 0.5))
# Draw tree at this position
t.penup()
t.goto(x_pos, y_base)
t.setheading(90) # Point up
t.pendown()
t.color('saddlebrown')
# Randomize tree shape slightly
angle = random.uniform(20, 35)
shrink = random.uniform(0.65, 0.8)
draw_tree(t, size, angle, shrink, size * 0.15)
# Recursively draw remaining trees, splitting the space
mid = (x_start + x_end) / 2
if random.random() > 0.5:
# Draw left side next
draw_forest_recursive(t, num_trees - 1, x_start, mid - 10, y_base,
min_size, max_size, depth + 1)
draw_forest_recursive(t, num_trees - 1, mid + 10, x_end, y_base,
min_size, max_size, depth + 1)
else:
# Draw right side next
draw_forest_recursive(t, num_trees - 1, mid + 10, x_end, y_base,
min_size, max_size, depth + 1)
draw_forest_recursive(t, num_trees - 1, x_start, mid - 10, y_base,
min_size, max_size, depth + 1)
def draw_cloud(t, x, y, size):
"""Draws a fluffy cloud."""
t.penup()
t.goto(x, y)
t.pendown()
t.color('white')
t.pensize(1)
for _ in range(5):
t.begin_fill()
t.circle(size * random.uniform(0.8, 1.2))
t.end_fill()
t.penup()
t.forward(size * 1.2)
t.right(random.uniform(-20, 20))
t.pendown()
def main():
# Setup screen
screen = turtle.Screen()
screen.setup(1200, 800)
screen.bgcolor('skyblue')
screen.title("Recursive Forest")
screen.tracer(0, 0) # Fastest drawing
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
# Draw sun
draw_sun(t, 400, 300, 40)
# Draw clouds
for _ in range(3):
draw_cloud(t, random.randint(-500, 300),
random.randint(200, 350),
random.randint(20, 35))
# Draw ground
draw_ground(t, 1200, 800)
# Draw forest recursively
# Parameters: turtle, num_trees, x_start, x_end, y_base, min_size, max_size
draw_forest_recursive(t, 8, -550, 550, -100, 60, 120)
# Add some bushes in foreground
t.color('darkgreen')
for _ in range(15):
x = random.randint(-580, 580)
y = random.randint(-250, -150)
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
t.circle(random.randint(15, 30))
t.end_fill()
screen.update()
screen.mainloop()
if name == "main":
main()
#!/usr/bin/env python3 """ Recursively draws a 2‑D forest of pine‑trees using the turtle graphics module. """ import turtle import random import math # ----- Configuration ----- NUM_TREES = 15 # Number of trees to draw MAX_DEPTH = 7 # Depth of recursion for each tree MIN_BASE_LEN = 60 # Minimum length of the trunk MAX_BASE_LEN = 120 # Maximum length of the trunk ANGLE_VARIANCE= 15 # +/- degrees of random variation for branching SIZE_VARIANCE = 0.7 # Size scaling factor for branches # ----- Utility functions ----- def random_color(): """Return a random greenish color for foliage.""" r = random.randint(0, 50) / 255 g = random.randint(100, 255) / 255 b = random.randint(0, 50) / 255 return (r, g, b) def draw_tree(t, length, depth): """ Recursive function that draws a single trunk/branch. """ if depth == 0 or length < 5: # Draw a leaf t.dot(7, random
import turtle
import random
def draw_tree(t, length, width, level, max_level, angle, spread):
"""
Recursively draws a tree-like branching structure.
t: turtle
length: current branch length
width: current branch thickness
level: current recursion depth
max_level: maximum recursion depth
angle: base branch angle
spread: how much each branch angle varies
"""
if level > max_level or length < 2:
return
# Draw branch
t.pensize(width)
t.forward(length)
# Color shifts with depth
# (deeper branches are lighter/greener)
ratio = level / max_level
r = int(20 + 80 * (1 - ratio))
g = int(80 + 120 * (1 - ratio))
b = int(20 + 80 * (1 - ratio))
t.pencolor(r, g, b)
# At deeper levels, draw a small "leaf" blob instead of more recursion
if level == max_level:
t.dot(width + 2)
t.backward(length)
return
# Branching (two or three branches)
num_branches = random.choice([2, 3])
for _ in range(num_branches):
t.save = True # no-op; just for readability
t.left(angle + random.uniform(-spread, spread))
draw_tree(t, length * random.uniform(0.68, 0.82),
width * 0.7, level + 1, max_level, angle, spread)
t.right(2 * (angle + random.uniform(-spread, spread)))
draw_tree(t, length * random.uniform(0.68, 0.82),
width * 0.7, level + 1, max_level, angle, spread)
# Undo the turn (we'll fix position by coming back below)
t.left(angle + random.uniform(-spread, spread))
# Move back to the start of this branch
t.backward(length)
def draw_forest(
tree_count=9,
x_start=-250,
x_end=250,
base_y=-250,
max_level=6
):
screen = turtle.Screen()
screen.title("Recursive Forest")
screen.bgcolor("black")
t = turtle.Turtle(visible=False)
t.speed(0)
t.penup()
t.setposition(x_start, base_y)
t.pendown()
t.hideturtle()
# Draw each tree with a slightly different size/seed
xs = [x_start + i * (x_end - x_start) / (tree_count - 1) for i in range(tree_count)]
for i, x in enumerate(xs):
t = turtle.Turtle(visible=False)
t.speed(0)
t.hideturtle()
t.penup()
t.setposition(x, base_y)
t.pendown()
# Randomize appearance
angle = random.uniform(15, 28)
spread = random.uniform
import turtle
import random
def draw_tree(branch_length, t, angle=20, shrink=0.7):
"""
Recursively draw a tree using turtle graphics.
Args:
branch_length: Length of the current branch
t: Turtle object
angle: Angle for branches (default 20 degrees)
shrink: Factor to shrink branches (default 0.7)
"""
if branch_length < 5: # Base case: stop when branches are too small
return
# Set color based on branch length (brown for trunk, green for leaves)
if branch_length < 12:
t.color("green")
t.pensize(1)
else:
t.color("brown")
t.pensize(branch_length / 10)
# Draw the current branch
t.forward(branch_length)
# Save position for returning
pos = t.position()
heading = t.heading()
# Recursive case: draw right branch
t.right(angle)
draw_tree(branch_length * shrink, t, angle, shrink)
# Return to saved position
t.penup()
t.goto(pos)
t.setheading(heading)
t.pendown()
# Recursive case: draw left branch
t.left(angle)
draw_tree(branch_length * shrink, t, angle, shrink)
# Return to saved position
t.penup()
t.goto(pos)
t.setheading(heading)
t.pendown()
def draw_forest(num_trees=7):
"""
Draw a forest with multiple trees.
Args:
num_trees: Number of trees to draw
"""
# Setup
screen = turtle.Screen()
screen.bgcolor("lightblue")
screen.title("Recursive Forest")
screen.setup(width=800, height=600)
t = turtle.Turtle()
t.speed(0) # Fastest drawing
t.hideturtle()
# Draw ground
t.penup()
t.goto(-400, -200)
t.pendown()
t.color("darkgreen")
t.begin_fill()
for _ in range(2):
t.forward(800)
t.left(90)
t.forward(100)
t.left(90)
t.end_fill()
# Draw trees at random positions
for i in range(num_trees):
# Position tree
x = random.randint(-350, 350)
y =
import turtle
import random
def draw_branch(branch_length, t, recursion_depth=0, max_depth=8):
"""Recursively draw branches with decreasing size and random angles."""
if recursion_depth > max_depth or branch_length < 3:
return
# Draw the current branch
t.forward(branch_length)
# Set colors based on depth (brown trunk, green leaves)
if recursion_depth < max_depth - 2:
t.color("saddlebrown")
else:
t.color("darkgreen")
# Save current position
pos = t.position()
heading = t.heading()
# Draw right branch
t.setheading(heading)
t.right(random.randint(20, 35))
draw_branch(branch_length * random.uniform(0.6, 0.8), t, recursion_depth + 1, max_depth)
# Draw left branch
t.penup()
t.setposition(pos)
t.setheading(heading)
t.pendown()
t.left(random.randint(20, 35))
draw_branch(branch_length * random.uniform(0.6, 0.8), t, recursion_depth + 1, max_depth)
# Return to starting position
t.penup()
t.setposition(pos)
t.setheading(heading)
t.pendown()
# Complete the branch
t.backward(branch_length)
def draw_tree(x, y, size=40):
"""Draw a complete tree at given coordinates."""
t = turtle.Turtle()
t.speed(0) # Fastest drawing
t.hideturtle()
t.penup()
t.goto(x, y)
t.setheading(90) # Point up
t.pendown()
draw_branch(size, t)
def draw_forest(num_trees=8):
import random
def draw_tree(height, indent=0):
"""
Recursively draw a single tree using ASCII art.
Each level of recursion draws one layer of the tree.
"""
if height <= 0:
return []
# Base case: trunk (last level)
if height == 1:
return [' ' * indent + '|']
# Recursive case: draw current layer and then the rest
leaves = ' ' * (indent + height - 1) + '*' * (2 * height - 1)
result = [leaves]
# Recursively draw the layer below
result.extend(draw_tree(height - 1, indent + 1))
return result
def draw_forest(num_trees, max_height=6, width=50):
"""
Recursively generate a forest by drawing multiple trees.
Uses recursion to iterate through tree count instead of a for-loop.
"""
if num_trees <= 0:
return []
# Draw one tree with random height
tree_height = random.randint(2, max_height)
tree_art = draw_tree(tree_height)
# Recursively generate the rest of the forest
rest_of_forest = draw_forest(num_trees - 1, max_height, width)
return tree_art + rest_of_forest
def print_forest():
"""Print the recursively generated forest."""
print("\n🌲 Welcome to the Recursive Forest! 🌲\n")
forest = draw_forest(10) # Generate 10 trees recursively
for line in forest:
print(line)
print("\n<-- That's a forest made with recursion! -->\n")
# Run it!
if name == "main":
print_forest()
import turtle import random # Set up the screen screen = turtle.Screen() screen.bgcolor("skyblue") # Create a turtle for drawing pen = turtle.Turtle() pen.speed(0) pen.left(90) # Point upwards pen.penup() def draw_tree(branch_length, pen): """Recursive function to draw a tree branch.""" if branch_length > 5: # Draw the branch pen.pensize(branch_length / 10) pen.pendown() pen.forward(branch_length) # Right branch angle = random.randint(15, 45) pen.right(angle) draw_tree(branch_length - random.randint(10, 20), pen) # Left branch pen.left(angle * 2) draw_tree(branch_length - random.randint(10, 20), pen) # Back to the original branch direction pen.right(angle) pen.penup() pen.backward(branch_length) else: # Draw a leaf at the end of branch pen.pendown() pen.dot(7, "green") pen.penup() def draw_forest(num_trees, width, height): """Draws a forest with num_trees randomly spread out over a given width and height.""" for _ in range(num_trees): # Random position for the trunk base x = random.randint(-width//2, width//2) y = random.randint(-height//2, -50) # Close to bottom of the screen pen.penup() pen.goto(x, y) pen.setheading(90) pen.pensize(1) draw_tree(random.randint(50, 100), pen) # Parameters: number of trees, screen width, screen height draw_forest(15, 600, 400) pen.hideturtle() screen.mainloop()