Forest
A few trees at fixed locations
Using list of lists, we can put trees at selected locations with varying height and width (x, z, h, w):
data = [
[-10,-20, 10, 3],
[-2, -18, 8, 4],
[15,-15, 20, 6],
[20, -25, 12, 3]
]
for i in data:
tree(i[0], i[1], i[2], i[3])
When defining a long list, you can split it into multiple lines as in the above example. This makes the code easier to read. But you have to put the opening bracket on the first line so that Python knows that line is not finished yet, and will look at the following lines until it finds the matching closing bracket.
Build a row of trees with for loop
Another example to build 10 trees along x-axis:
for i in range(-40, 40, 10):
tree(i, -30, 20, 4)
A forest with many trees
Build trees of random sizes at random locations
In previous lessons, we have used randint()
to generate random integers. For example, to put 10 blocks at random locations:
# 10 brick blocks at random (x, y, z) locations
for i in range(10):
block(randint(1, 20), randint(1, 20), randint(-20, -10), 'brick')
Similarly, we can use randint()
in tree()
to generate a lot of trees at random locations, with random height and width.
# Forest
# Generate 20 random sized trees at random locations
for n in range(1,20):
tree(randint(-20, 40), randint(-40, -10), randint(10, 20), randint(2, 4))
Every time we run the program Forest
, we get a different looking forest,
(Optional): A Fantasy Forest
Build trees with random colorful materials, e.g. from 45 to 59 (the linen
series). You will get a beautiful forest like this:
The world has become more colorful!