使用 Python 的海龟模块绘制此图案。一些正方形彼此重叠但倾斜有点像螺旋

Drawing this pattern using Python’s turtle module. Some squares on top of each other but tilted sort of like a spiral

我是编程新手,正在阅读一本名为《如何像计算机科学家一样思考》的书。第四章讲的是函数

在本章的最后,有一个练习要求我使用 Python 的海龟模块绘制以下图案。

我正在检查这张照片并决定将它分成两部分:1) 中间的线条和 2) 像螺旋一样相互重叠的正方形。

我用这段代码画了第一部分:

import turtle

wn = turtle.Screen()  # Set up the window
wn.bgcolor("lightgreen")

alex = turtle.Turtle()  # Create Alex
alex.color("blue")
alex.pensize(3)

for i in range(20):  # Here I start drawing the lines
    alex.forward(100)
    alex.backward(100)
    alex.left(360/20)  # Fit 20 lines in the 360 degree circle

wn.mainloop()

当我运行它时,它画了这个:

然后,我创建了 draw_square 函数并成功绘制了第一个正方形:

import turtle


def draw_square(turtle, size):
    for i in range(4):
        turtle.forward(size)
        turtle.left(90)


wn = turtle.Screen()  # Set up the window
wn.bgcolor("lightgreen")

alex = turtle.Turtle()  # Create Alex
alex.color("blue")
alex.pensize(3)

for i in range(20):  # Here I start drawing the lines
    alex.forward(100)
    alex.backward(100)
    alex.left(360/20)  # Fit 20 lines in the 360 degree circle

# In a messy way, using what I've learned, I move Alex to where he's supposed to be now
# I'm pretty sure there's a classier way to do this
alex.penup()
alex.backward(100)
alex.right(90)
alex.forward(100)
alex.left(90)
alex.pendown()

# Here I get Alex to draw the square
draw_square(alex, 200)

wn.mainloop()

当我运行它时,它画了这个:

现在我卡住了。我不知道从这里去哪里。我不知道如何着手绘制所有其他方块。我不知道把乌龟放在哪里,把正方形倾斜多少度(大概是 20 度,就像线条一样,但我不知道如何实现)……总之,你们有什么建议吗?有什么建议吗?

我尽量不跳过书中的任何练习,而这一个让我明白了。

出色的尝试,感谢 expected/actual 输出的清晰图像!

该模式实际上比您想象的要简单一些。从中心重复绘制一个盒子,每次迭代时海龟都会在中心点上稍微旋转。盒子边的重叠创造了 "spokes" 的错觉。

至于以度为单位确定转弯量,我用 360 将其除以图像中显示的辐条数 (20),得到 18 度。

这是生成正确输出的代码。

import turtle

def draw_square(turtle, size):
    for i in range(4):
        turtle.forward(size)
        turtle.left(90)

if __name__ == "__main__":
    wn = turtle.Screen()
    wn.bgcolor("lightgreen")
    alex = turtle.Turtle()
    alex.color("blue")
    alex.pensize(3)
    boxes = 20

    for _ in range(boxes):
        draw_square(alex, 200)
        alex.left(360 / boxes)

    wn.mainloop()

输出: