1
我有這段代碼,它讀取並解析分形描述語言文件,然後使用FractalWorld,這是TurtleWorld的特殊版本,它只是去除烏龜,並沒有延遲。使用分形,類和swampy製作二叉樹TurtleWorld - Python - 調試
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()
的FDL文件將作出二叉樹,它看起來像這樣:
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
我的問題是有一個bug,在我的翻譯。看起來解釋器沒有正確讀取比例尺,而是按比例縮放我的線條作爲樹枝的下一個深度。我試圖調試它,但一直沒能做到。
我在哪裏可以找到'FractalWorld'? – User