Build a natural looking tree

A natural looking tree shouldn't have solid leaves. Instead, there should be random empty spaces among the leaves.

We will use randint() in random module. Make sure to import randint() at the top of the program. Add this line to the beginning of the program if it's not already there:

from random import randint

Y_tree_line

First we need a vertical leaves line that has random empty spots:

# Y_tree_line
def Y_tree_line(x, y, z, h, m):
    for j in range(h):
        block(x, randint(y, y+h), z, m)

Build 3 y_tree_lines, these lines break at random locations just like natural tree leaves.

# three tree lines                                                                                                                                                                                              
Y_tree_line(20, 15, -10, 12, 'leaves')   
Y_tree_line(22, 15, -10, 12, 'leaves')   
Y_tree_line(24, 15, -10, 12, 'leaves') 

# bar_y, at the left 
bar_y(1, 15, -10, 12, 'leaves')

Compare these tree leave lines with a solid green bar_y at the very left.

treeN()

Let's use y_tree_line to build a natural looking tree:

# tree trunk
column(10, -10, 20, 'log_big_oak')

# tree top
for i in range(9, 12):
        for k in range(-11, -8):
            Y_tree_line(i, 12, k, 10, 'leaves')

It looks like we can define a function to build a few natural looking 'tree' and see the effect of randint()

treeN(x,z,h)

# treeN, total height, h
def treeN(x,z,h):
    column(x,z,h, 'log_big_oak')

    for i in range(x-1, x+2):
        for k in range(z-1,z+2):
            Y_tree_line(i, (int(h/2)+2), k, int(h/2), 'leaves')

Here, h is the total height of the tree, tree top has about half of the total height, h/2 might be a floating number, so I use type conversion int(h/2).

Three treeN

treeN(20, -10, 20)  
treeN(25, -10, 20) 
treeN(30, -10, 20)

Better than popsicles.

results matching ""

    No results matching ""