I have this piece of code, which read and then interpretes a Fractal description language file, then uses FractalWorld, Which is a special version of TurtleWorld, which just removes the turtle and has no delays.
import math, random, sys
from FractalWorld import *
world = FractalWorld(width=1000,height=1000,delay=0)
Rasmus = Fractal(draw=False)
class command(object):
def __init__(self, cmd, l):
self.cmd = cmd
self.l = l
def execute(self, turtle, length):
if self.cmd=='lt':
lt(turtle, int(self.l[0]))
if self.cmd=='rt':
rt(turtle, int(self.l[0]))
if self.cmd=='fd':
fd(turtle, length)
if self.cmd=='bk':
bk(turtle, length)
if self.cmd=='scale':
lenght = length*float(self.l[0])
class rule(object):
def __init__(self):
self.rule={} #we make an empty dictionary
def newrule(self,leftside,rightside):
self.rule[leftside]=rightside #we fill the dictionary
def expand (self,oldlist,depth):
if depth <= 0:
return oldlist
newlist=[] # we make an empty new list
for i in oldlist:
if i not in self.rule:
newlist.append(i)
else:
newlist.append(self.expand(self.rule[i],depth-1))
return newlist
class Fractal(object):
def __init__(self, start, rules, commands, length, depth):
self.start = start
self.rules = rules
self.commands = commands
self.length = length
self.depth = depth
def draw(self, oldlist):
for i in oldlist:
if type(i) == list:
self.draw(i)
else:
cmd = self.commands[i]
cmd.execute(Rasmus, self.length)
def read():
files = open('tree.fdl')
commands = {}
r = rule()
for line in files:
line = line.strip()
oldlist = line.split(' ')
if oldlist[0] == 'start':
start = oldlist[1:]
elif oldlist[0] == 'rule':
r.newrule(oldlist[1], oldlist[3:])
elif oldlist[0] == 'cmd':
cmd = command(oldlist[2], oldlist[3:])
commands[oldlist[1]] = cmd
elif oldlist[0] == 'length':
length = int(oldlist[1])
elif oldlist[0] == 'depth':
depth = int(oldlist[1])
return Fractal(start, r, commands, length, depth)
re = read()
print re.commands.keys()
l = re.rules.expand(re.start , re.depth)
re.draw(l)
wait_for_user()
The fdl file will make an binary tree and it looks like this:
start X
rule X -> F L D X R X U L B
length 100
depth 10
cmd X nop
cmd F fd
cmd B bk
cmd R rt 70
cmd L lt 35
cmd D scale 0.7
cmd U scale 1.4285714285714286
My problem is there is a bug, in my interpreter. It seems that the interpreter does not read the scale correct and down scales my lines for the next depth of the trees branches. I have tried to debug it but haven't been able to do it.
lenght = length*float(self.l[0])
This line has two bugs. First, a typo. But then even if the name was correct, you'd be assigning a new value to a local variable as the last thing you do in the function, which is pointless. You probably should replace it with xxx.length
so that calling the function can change its value. The object I wrote as xxx
could be the Fractal instance available at the caller; then you'd pass it as an argument, instead of the length
.