Kodewick
開始學 →

Python 愛心程式碼

一顆大紅心,周圍飄著小愛心。愛心是用兩段半圓和兩條直線拼出來的。

Python 愛心程式碼
完整程式碼(37 行)
import turtle
import random

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


def heart(x, y, size, color):
    # 從愛心最下面的尖開始畫
    t.penup()
    t.goto(x, y)
    t.setheading(45)
    t.pendown()
    t.color(color)
    t.begin_fill()
    t.forward(size)
    t.circle(size / 2, 180)
    t.right(90)
    t.circle(size / 2, 180)
    t.forward(size)
    t.end_fill()


# 周圍飄著的小愛心
for i in range(14):
    heart(random.randint(-260, 260), random.randint(-200, 200), random.randint(12, 26), random.choice(["pink", "hotpink", "lightpink"]))

# 中間的大愛心
heart(0, -130, 160, "red")

t.penup()
t.goto(0, 10)
t.color("white")
t.write("我喜歡你", align="center", font=("Arial", 30, "bold"))

怎麼畫的

愛心從最下面的尖開始:setheading(45) 朝右上走一條直線,circle(size / 2, 180) 畫半個圓,右轉 90 度再畫半個圓,最後一條直線回到尖。

整個過程夾在 begin_fill() 和 end_fill() 中間,圍出來的形狀就塗滿顏色。

把這些步驟包成函式 heart(x, y, 大小, 顏色),小愛心和大愛心就都用它畫:小的隨機位置、隨機大小。

字用 t.write(...) 寫在愛心中間,align="center" 讓字居中。

常見問題

怎麼換成 TA 的名字?

點「改一改」,把 write 括號裡的「我喜歡你」換成別的字(引號用英文的)再執行。

愛心畫歪了?

畫愛心前要 setheading(45) 把方向擺正。如果之前轉過方向又沒擺正,愛心就會歪。

能做成會跳動的愛心嗎?

可以:用 tracer(0)、clear() 和 ontimer,每幀把大小變一點再畫。可以參考「跨年煙花」那一頁的動畫寫法。

換個樣子