Drawing trees with turtles

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:

Turtle tree simple

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:

Turtle tree color

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

  tree(d*f, n-1)

  tree(d*f, n-1)

  tree(d*f, n-1)
  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

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



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.

You should get a copy of my slick ZeroBrane Studio IDE and follow me on twitter here.

Leave a comment

what will you say?


I am Paul Kulchenko.
I live in Kirkland, WA with my wife and three kids.
I do consulting as a software developer.
I study robotics and artificial intelligence.
I write books and open-source software.
I teach introductory computer science.
I develop a slick Lua IDE and debugger.