I have been working on a simple Turtle graphics library for my seven year old son and showed him some intermediate results. One of them was a simple fractal tree that looked like this:
My son immediately got excited and wanted to come up with possible ways to change the drawing. His first idea was to color the tree and to make the trunk brown and the leaves green. Then he wanted to make the trunk wider. After that he wanted a smaller tree and grass. Then he wanted to add flowers; at this point I decided to stop, as the tree already looked good and the flowers required a different fractal. Here is the tree we generated:
The grass pattern is generated using exactly the same logic as the tree, just with a smaller level limit, repeated multiple times with some random shift. The code turned out to be quite simple:
require "turtle"
local f=0.5 -- how much shorter the next tree should be
local a=60 -- what angle to use to turn the branches
function tree(d, n) -- distance to grow, level for recursion
if n == 0 then return end
local width = pnsz(n) -- set pen size; save current value
local color = pncr(colr(127,(8-n)*32,0)) -- set pen color
move(2/3*d)
turn(a)
tree(d*f, n-1)
turn(-a)
move(1/3*d)
turn(-a)
tree(d*f, n-1)
turn(a)
turn(7)
tree(d*f, n-1)
turn(-7)
move(-1/3*d) -- note that 1/3+2/3 is not always 1
move(-2/3*d) -- so move back in the same way as forward
pncr(color) -- restore pen color to make it work recursively
pnsz(width) -- restore pen size to make it work recursively
wait(0.001) -- slow down the drawing
end
turn(-90) -- point turtle up as trees grow up
-- grow a large tree
goto(0, 120)
tree(160, 7)
-- grow a small bush
goto(-80, 120)
tree(80, 6)
-- grow grass
for grass = -180,180 do
goto(grass+rand(5),120+rand(25))
tree(8,3)
end
save("tree")
wait()
The same method tree()
is used to generate both of the trees and the grass; the only difference is the size and the "depth" of the tree: tree(160, 7)
, tree(80, 6)
, and tree(8,3)
.
The turtle
library only depends on wxWidgets
library for Lua. You can use ZeroBrane Studio to run these scrips, the development environment for Lua I developed specifically for students to learn programming and to work on simple script like this one. This development environment already includes wxWidgets
library and also allows users to debug applications, which makes it easy to learn how things work.
Leave a comment