Python使用类生成分形树

时间:2017-03-21 09:33:33

标签: python svg

我想使用SVG路径对象生成分形树。树的一个分支应该由一个Branch对象表示。我的递归逻辑和收集path有问题。对于depth=1,代码应生成4 path s,但我当前的代码只返回一个path。我怎么能纠正这个?

我的代码:

import math


class Branch:

    def __init__(self, pointxy1, pointxy2):
        self.pointXY1 = pointxy1
        self.pointXY2 = pointxy2

    def __str__(self):
        return (r'<path d="M {} {} L {} {}"'' '
                'stroke="rgb(100,60,0)" stroke-width="35"/>')\
            .format(self.pointXY1[0], self.pointXY1[1], self.pointXY2[0], self.pointXY2[1])

    def drawtree(self, lenght, angle, depth):

        if depth:
            self.pointXY2[0] = self.pointXY1[0] + lenght * (math.cos(math.radians(angle)))
            self.pointXY2[1] = self.pointXY1[1] + lenght * (math.cos(math.radians(angle)))

            self.drawtree(lenght, angle - 20, depth - 1)
            self.drawtree(lenght, angle, depth - 1)
            self.drawtree(lenght, angle + 20, depth - 1)

        return Branch(self.pointXY1, self.pointXY2)

tree = [Branch([400, 800], [400, 600]).drawtree(200, -90, 1)]

for t in tree:
    print t

以下是输出。这只是一条路而不是所需的路径。

<path d="M 400 800 L 400 600" stroke="rgb(100,60,0)" stroke-width="35"/>

编辑:

这是我的非对象示例:

import math


def drawTree(lenght, angle, depth):

    if depth >= 0:

        x1 = 400
        y1 = 800

        x2 = x1 + lenght * (math.cos(math.radians(angle)))
        y2 = y1 + lenght * (math.sin(math.radians(angle)))

        print (r'<path d="M {} {} L {} {}"'' stroke="rgb(100,60,0)" stroke-width="35"/>').format(x1, y1, x2, y2)

        drawTree(lenght, angle - 20, depth - 1)
        drawTree(lenght, angle, depth - 1)
        drawTree(lenght, angle + 20, depth - 1)


drawTree(200, -90, 1)

输出:

<path d="M 400 800 L 400.0 600.0" stroke="rgb(100,60,0)" stroke-width="35"/>
<path d="M 400 800 L 331.595971335 612.061475843" stroke="rgb(100,60,0)" stroke-width="35"/>
<path d="M 400 800 L 400.0 600.0" stroke="rgb(100,60,0)" stroke-width="35"/>
<path d="M 400 800 L 468.404028665 612.061475843" stroke="rgb(100,60,0)" stroke-width="35"/>

结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

构建一个平面列表,然后迭代它以打印它:

def drawtree(self, lenght, angle, depth):
    result = []
    if depth:
        self.pointXY2[0] = self.pointXY1[0] + lenght * (math.cos(math.radians(angle)))
        self.pointXY2[1] = self.pointXY1[1] + lenght * (math.cos(math.radians(angle)))

        result.extend(self.drawtree(lenght, angle - 20, depth - 1))
        result.extend(self.drawtree(lenght, angle, depth - 1))
        result.extend(self.drawtree(lenght, angle + 20, depth - 1))

    result.append(Branch(self.pointXY1, self.pointXY2))
    return result

答案 1 :(得分:1)

您正在对drawTree进行这些调用,但是您没有使用返回值执行任何操作:

drawTree(lenght, angle - 20, depth - 1)
drawTree(lenght, angle, depth - 1)
drawTree(lenght, angle + 20, depth - 1)

所以返回的分支刚刚丢失。它没有添加到您的树中。

你的“非对象示例”似乎有效的原因是你在drawTree函数中进行打印,所以你会为每个分支打印一些东西。你真的遇到了同样的问题而且还丢失了返回值,只是你先打印一些东西。