我的代码无法生成如上所示的对称毕达哥拉斯树。
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()
使用列表推导式对正方形进行缩放(使用 cos / sin)并移动。
但是我无法将旋转和缩放的方块移动到正确的位置。
我尝试过: