Smalltalk Fractal Trees

Making Fractal Trees in Smalltalk is pretty simple, especially with Squeak, which has lots of drawing classes included out of the box.

All the drawing in the example below is done with the Pen class, I've used recursion to build up the tree branch by branch—there's not much code so you should be able to see what's going on—plus there's some example enhancements at the end of the page.

Start by opening a new Browser from the Tools menu, right click in the first column and add a new category to contain your new class. I called mine 'GeekClub', but you can pick whatever name you like. Now add this new class...

Object subclass: #FractalTree
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'GeekClub'

Add these two methods to the class...

tree: aPoint length: aLength angle: anAngle
| p a |

(aLength > 10) ifTrue: [
p := Pen new.
p up.
p goto: aPoint.
p turn: anAngle.
p down.
5 timesRepeat: [
p go: aLength / 5.
p turn: 5.
].
a := anAngle - 30.
3 timesRepeat: [
self tree: p location length: aLength * 0.7 angle: a.
a := a + 30.
]
].

draw
Display restoreAfter: [
Display fillWhite.
self tree: 700@700 length: 200 angle: 0.
]

Now open a Workspace and enter:

FractalTree new draw.

You should see a fractal tree like the one above. Click to return to the code view.

Improvements

There's lots of improvements you can make to the above code, try these:

Make thicker branches at the base, add this to the tree method after p up.
p squareNib: aLength / 25.

Add a bit of randomness to the angle between branches, replace a := a + 30. with
a := a + 30 + (20 atRandom).

Find out more

There's a great, free PDF book here if you want to find out more about Squeak: http://squeakbyexample.org/ and the official Squeak site: http://www.squeak.org/

1 comment:

1. brilliant appreciate the posts especialy on the graphics