Pythagoras Tree

Nothing fancy, but I tried one of my first exercises from my first year of computer science. Drawing a Pythogoras Tree recursively. Back then we used Modula-2. The ironic part is that Modula-2 had no drawing functionality whatsoever, so we had to dump every calculated vector in a format that would be read in by some other software to visualise it.

Now in Python:

# Pythagoras
# Draws a Pythagoras Tree of n depth

import math
import turtle

# initialize - create t object and sets it in starting position
t = turtle.Pen()
t.penup()
t.left(90)
t.back(200)
t.pendown()

def tree(base, n):
    if n == 0:
        return
    else: # draw a tree
        new_base = math.sqrt((base*base)/2)
        t.forward(base)
        left_branch(new_base, n-1)
        t.right(90)
        t.forward(base)
        right_branch(new_base, n-1)
        t.right(90)
        t.forward(base)
        t.right(90)
        t.forward(base)
        t.right(90)
        return

def left_branch(base, n): 
# sets the turtle in the right angle and calls tree()
    if n == 0:
        return
    else:
        t.left(45)
        tree(base, n)
        t.right(45)
        return

def right_branch(base, n): 
# sets the turtle in right position and angle and calls tree()
    if n == 0:
        return
    else:
        t.left(135)
        t.forward(base)
        t.right(90)
        tree(base, n)
        t.right(90)
        t.forward(base)
        t.left(45)

tree(100,10)

recursiveTraaHowever much I like recursive functions for their elegance (and I do admit there are much better examples of elegance than my Pythagoras Tree), I do not care much for this recursive tree as it is drawn on the screen. You can see the tree develop itself in a n-depth from left to right manner. Which means until the first call of tree() finishes the tree has no complete trunk to stand on.

I think it would be better to have a tree object with a grow method so that everytime tree.grow() is called the tree grows a little new tree from each existing branch. I don’t know how to do that yet. But when I do I’ll post it.

Here is the complete tree with depth n = 10.

recursiveTreeFinished

 

 

Advertenties

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit / Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit / Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit / Bijwerken )

Google+ photo

Je reageert onder je Google+ account. Log uit / Bijwerken )

Verbinden met %s