我是编程新手,正在读一本名为《如何像计算机科学家一样思考》的书。第四章讲函数。
在本章的最后,有一个练习要求我使用Python的turtle模块绘制以下图案。
我正在检查这张图片,并决定将其分成两部分: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度,就像线条一样,但我不知道如何实现)……不管怎样,你们有什么建议吗?有什么建议吗?
我尽量不跳过书上的任何练习,而这个练习抓住了我。
出色的尝试,感谢您提供预期/实际输出的清晰图像!
该模式实际上比您想象的要简单一些。从中心重复绘制一个盒子,每次迭代时海龟都会在中心点上稍微旋转。盒子侧面的重叠产生了“辐条”的错觉。
至于确定转动量(以度为单位),我将 360 除以图像中显示的辐条数量 (20),得到 18 度。
这是产生正确输出的代码。
from turtle import Turtle
def draw_square(turtle, size):
for i in range(4):
turtle.forward(size)
turtle.left(90)
def main():
turtle = Turtle()
turtle.getscreen().bgcolor("lightgreen")
turtle.color("blue")
turtle.pensize(3)
boxes = 20
for _ in range(boxes):
draw_square(turtle, 200)
turtle.left(360 / boxes)
turtle.getscreen().exitonclick()
if __name__ == "__main__":
main()
输出: