mbach21
mbach21

Reputation: 23

Python: 3 branched tree

What i want it to look like

results

I figured out how to make a tree, but it spawns random designs at times. I'd like to know instead how to make a 3 branched tree where everything's in uniform. Thanks!

import turtle
import random

turtle.speed(0)
turtle.hideturtle()
turtle.tracer(0,0)

def draw_line(x,y,angle,length,color,size):
    turtle.up()
    turtle.goto(x,y)
    turtle.seth(angle)
    turtle.color(color)
    turtle.pensize(size)
    turtle.down()
    turtle.forward(length)


def draw_tree(x,y,angle,length,color,size,thiccness,n):
    if n == 0:
       return
    if n <= 3:
       color = 'lime green'
    draw_line(x,y,angle,length,color,size)
    cx = turtle.xcor()
    cy = turtle.ycor()
    draw_tree(cx,cy,angle-thiccness+random.uniform(-8,8),length/(1.3+random.uniform(-.2,.2)),color,size*(0.8+random.uniform(-.1,.1)),thiccness,n-1)
    draw_tree(cx,cy,angle+thiccness+random.uniform(-8,8),length/(1.3+random.uniform(-.2,.2)),color,size*(0.8+random.uniform(-.1,.1)),thiccness,n-1)

draw_tree(0,-350,90,150,'brown',10,30,10)
turtle.update()

Upvotes: 1

Views: 400

Answers (1)

cdlane
cdlane

Reputation: 41872

I have to say that I like the trees that your program currently generates as they are more like real trees and every one is different. If we remove the random element from your code, and add a middle branch, then we'll get the one uniform tree that you desire, and only the one uniform tree you desire:

from turtle import Screen, Turtle, Vec2D

THICKNESS = 30

def draw_line(position, angle, length, size, color):
    turtle.penup()
    turtle.goto(position)
    turtle.setheading(angle)
    turtle.color(color)
    turtle.pensize(size)
    turtle.pendown()
    turtle.forward(length)

def draw_tree(position, angle, length, size, color, n):
    if n == 0:
        return

    if n <= 3:
        color = 'green'

    draw_line(position, angle, length, size, color)

    position = turtle.position()
    length /= 1.4
    size *= 0.7

    draw_tree(position, angle - THICKNESS, length, size, color, n - 1)
    draw_tree(position, angle, length, size, color, n - 1)
    draw_tree(position, angle + THICKNESS, length, size, color, n - 1)

screen = Screen()
screen.tracer(False)

turtle = Turtle(visible=False)

draw_tree(Vec2D(0, -350), 90, 150, 10, 'brown', 9)

screen.update()
screen.tracer(True)
screen.exitonclick()

enter image description here

Upvotes: 1

Related Questions