Python用类生成分形树

2024-10-03 17:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用SVG路径对象生成一个分形树。树的一个分支应该由一个Branch对象表示。我的递归逻辑和收集path有一些问题。对于depth=1,代码应该生成4path,但是我当前的代码只返回一个这样的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

下面是输出。只有1条路径,而不是期望的4条路径。在

^{pr2}$

编辑:

这是我的非对象示例,它正在工作:

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


Tags: pathselfbranchstrokedefmathrgbwidth
2条回答

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

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

您对drawTree进行了以下调用,但没有对返回值执行任何操作:

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

所以返回的树枝就丢了。它不会添加到你的树中。在

您的“非对象示例”似乎起作用的原因是,您正在drawTree函数内执行打印操作,因此每个分支都会打印一些内容。不过,你确实有同样的问题,而且还降低了返回值,只是你先打印了一些东西。在

相关问题 更多 >