Code:
import turtle
import random
import time
screen = turtle.Screen()
screen.setup(700, 700)
screen.bgcolor("#02030a")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.width(2)
colors = [
"#00ff9d", "#00e5ff",
"#2979ff", "#9b30ff",
"#ff2d75"
]
def tree(length, angle, depth):
if depth == 0:
t.dot(7, random.choice(colors))
return
t.forward(length)
screen.update()
time.sleep(0.015)
pos = t.position()
heading = t.heading()
# Left branch
t.left(angle)
tree(length * 0.72, angle, depth - 1)
t.penup()
t.goto(pos)
t.setheading(heading)
t.pendown()
# Right branch
t.right(angle * 2)
tree(length * 0.72, angle, depth - 1)
t.penup()
t.goto(pos)
t.setheading(heading)
t.pendown()
t.penup()
t.goto(0, -300)
t.setheading(90)
t.pendown()
t.color("#00e5ff")
tree(110, 28, 8)
turtle.done()
Explanation:
1. Import Libraries
import turtle
import random
import time
turtle → Drawing.
random → Random colors.
time → Animation delay.
2. Create the Screen
screen = turtle.Screen()
screen.setup(700, 700)
screen.bgcolor("#02030a")
Creates a 700 × 700 dark canvas.
3. Configure the Turtle
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.width(2)
Creates the turtle.
Hides the cursor.
Uses maximum speed.
Sets line thickness.
4. Define Neon Colors
colors = [...]
Stores colors for the glowing tree tips.
5. Create the Recursive Tree Function
def tree(length, angle, depth):
Defines the fractal tree.
length → Branch size.
angle → Branch angle.
depth → Recursion level.
6. Set the Base Case
if depth == 0:
t.dot(7, random.choice(colors))
return
Stops recursion when depth reaches 0.
Adds a random-colored glowing dot.
7. Draw the Main Branch
t.forward(length)
Draws the current branch.
8. Save Turtle Position
pos = t.position()
heading = t.heading()
Saves the current position and direction.
Allows the turtle to return after each branch.
9. Create the Left Branch
t.left(angle)
tree(length * 0.72, angle, depth - 1)
Turns left.
Recursively creates a smaller branch.
10. Return to the Branch Point
t.penup()
t.goto(pos)
t.setheading(heading)
t.pendown()
Returns to the saved position.
Restores the original direction.
11. Create the Right Branch
t.right(angle * 2)
tree(length * 0.72, angle, depth - 1)
Turns right.
Creates another smaller branch recursively.
12. Set the Starting Position
t.goto(0, -300)
t.setheading(90)
Places the turtle at the bottom center.
Points it upward.
13. Draw the Tree
tree(110, 28, 8)
Starts the recursive tree.
8 gives multiple branching levels.
14. Finish
turtle.done()
Keeps the Turtle window open.

0 Comments:
Post a Comment