You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:无法生成对称Pythagoras Tree的Python代码问题

对称毕达哥拉斯树绘制问题

我编写的代码无法生成对称的毕达哥拉斯树。我通过cos/sin对正方形进行缩放,并使用列表推导式来移动位置,但无法将旋转和缩放后的正方形放置到正确位置。

我尝试过以下方法:

  • 使用[x.rotate(angle) * cos(angle) + points[1] for x in points]来将正方形移动到合适位置,但超过两层后就会出现问题。

我的代码

from turtle import *
from math import sin, cos


def main():
    t = Turtle()  # Initiate turtle to t
    t.speed(5)  # Set turtle speed

    window = Screen()  # Initialize window to draw
    window.bgcolor('white')
    window.tracer(True)

    # -- Parameters --
    level = 3  # Set the degree here
    length = 200
    a = 45  # Set the angle "alpha" here, must be less than 90
    points = [Vec2D(0, 0), Vec2D(0, length), Vec2D(length, length), Vec2D(length, 0)]

    pythTree(t, length, level, a, points)

    # Program ends
    window.exitonclick()


def pythTree(t, length, level: int, angle: int, points) -> None:

    if level > 0:

        drawSquare(t, points)

        # Calculate the lengths of the next two squares
        lengths = scaleLength(length, angle)
        # Calculate the position of the squares in the recursive call

        # -- Recursive Calls --
        pythTree(t, lengths[0], level - 1, angle, [x.rotate(angle) * cos(angle) for x in points])  # Left Side BC

        pythTree(t, lengths[1], level - 1, angle, [x.rotate(-angle) * sin(angle) for x in points])  # Right Side AC


def drawSquare(t, points) -> None:

    t.begin_fill()
    for point in points:
        t.goto(point)
    t.goto(points[0])
    t.end_fill()
    update()


def scaleLength(length, angle: int) -> tuple[int | float, int | float]:
    # LEFT SIDE: BC
    BC = cos(angle) * length
    # RIGHT SIDE: AC
    AC = sin(angle) * length
    return BC, AC


if __name__ == '__main__':
    main()

内容的提问来源于stack exchange,提问作者RE2XX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:00:31