Kodewick
開始學 →

Python 畫向日葵

花盤裡的種子每顆轉 137.5 度(黃金角),自然排出一圈圈螺旋。把這個角度改一點點,螺旋就亂了。

Python 畫向日葵
完整程式碼(36 行)
import turtle
import math

screen = turtle.Screen()
screen.bgcolor("lightskyblue")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def petal(angle, size):
    t.penup()
    t.goto(0, 0)
    t.setheading(angle)
    t.forward(70)
    t.pendown()
    t.color("orange", "gold")
    t.begin_fill()
    t.circle(size, 70)
    t.left(110)
    t.circle(size, 70)
    t.end_fill()


# 花瓣:一圈 34 片
petals = 34
for i in range(petals):
    petal(i * 360 / petals - 35, 80)

# 花盤:每顆種子轉 137.5 度(黃金角),越往外離中心越遠
t.penup()
for i in range(320):
    r = 4 * math.sqrt(i)
    a = math.radians(i * 137.508)
    t.goto(r * math.cos(a), r * math.sin(a))
    t.dot(6, "saddlebrown" if i % 2 else "#5a3418")

怎麼畫的

第 i 顆種子離中心 4 * math.sqrt(i)、方向轉 i * 137.508 度。開平方讓種子在面積上分佈均勻,不會擠在中間。

137.508 度是黃金角(360 度按黃金比例分開)。用這個角度,種子永遠不會排成直線,真的向日葵就是這樣長的。

math.radians 把度換成弧度,math.cos、math.sin 算出 x、y。

花瓣先畫、種子後畫:後畫的蓋在上面,所以花盤在花瓣上面。

常見問題

把 137.508 改成 137 或 140 會怎樣?

種子會排成一條條直的輻條,空出很多縫。這正是自然界選黃金角的原因:它讓種子擠得最密。

math 要裝嗎?

不用,math 是 Python 自帶的。

換個樣子