用 python 海龟重复函数

Repeating functions with python turtle

我想知道使函数循环重新创建具有不同旋转和位置以及不同变量(例如颜色)的相同 shape/pattern(google photo logo) 的方法。下面是允许我制作具有正确角度但比例不准确的托盘之一的代码。也最好不要使用任何 goto/home 函数,因为我需要稍后重复此绘图。我应该使用 left/right 作为方向而不是设置航向吗?

def photo():
    speed(1) # turtle speed (debugging)
    #speed(0)
    length = 50

    penup()
    color("#4688f4") #Blue petal
    begin_fill() 
    setheading(25)
    forward(length/5.5)
    setheading(0)
    forward(length)
    setheading(227)
    forward(length*0.87)
    setheading(135)
    forward(length*0.8)
    end_fill()

    color("#3d6ec9") #Blue petal
    begin_fill() 
    setheading(250)
    forward(length/5)
    setheading(270)
    forward(length/2.6)
    setheading(0)
    forward(length/1.6)
    end_fill() 

这里是代码图...

更新:

非常简单的答案:

my_colors =['blue', 'yellow', 'red', 'green'] # replace with hex values

for i in range(4):

    photo(my_colors[i])
    right(90)
然后需要调整

photo 函数以采用关键字,它可能看起来像:def photo(my_color):,在函数中使用颜色的地方,只需将其命名为 color(my_color)

但是你当然需要考虑在每个循环之后你会转向哪里,以及你是否还需要继续前进。

Why is there like weird gap on blue petal while others don't?

为了画得干净,我们需要某种几何模型。我将使用的是一对匹配的直角三角形,底边为 7 个单位,角为 45 度:

我在我认为合乎逻辑的 原点 处画了一个红点。为了保持数学上的一致性,我们将从上图中剪下我们想要的图像:

Should I have used left/right for direction instead of set heading?

绘制这个图形并旋转它的代码不能使用 setheading(),因为它是绝对的,我们必须相对于我们的逻辑原点绘制:

from turtle import *

UNIT = 50

def photo(petal, shadow):

    right(45)  # move from "origin" to start of image
    forward(0.45 * UNIT)
    left(70)

    color(petal)

    begin_fill()
    forward(0.752 * UNIT)
    right(25)
    forward(6 * UNIT)
    right(135)
    forward(4.95 * UNIT)
    end_fill()

    right(45)

    color(shadow)

    begin_fill()
    forward(3.5 * UNIT)
    right(90)
    forward(2.5 * UNIT)
    right(25)
    forward(0.752 * UNIT)
    end_fill()

    left(70)  # return to "origin" where we started 
    forward(0.45 * UNIT)
    right(135)

penup()

for _ in range(4):
    photo("#4688f4", "#3d6ec9")
    left(90)

hideturtle()
mainloop()

我会把着色问题留给你。