Python 生日蛋糕
三層蛋糕、奶油花邊、點著的蠟燭和「生日快樂」。蠟燭根數改成壽星的歲數,存圖發過去。

完整程式碼(59 行)
import turtle
import random
screen = turtle.Screen()
screen.bgcolor("#fff4e6")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
def box(x, y, w, h, color):
# 一個填色的長方形,左下角在 (x, y)
t.penup()
t.goto(x, y)
t.setheading(0)
t.pendown()
t.color(color)
t.begin_fill()
for side in [w, h, w, h]:
t.forward(side)
t.left(90)
t.end_fill()
# 盤子
box(-200, -170, 400, 12, "lightgray")
# 三層蛋糕,一層比一層窄
layers = [("#f7c6d9", 320, 90), ("#fbe3a1", 240, 75), ("#c9e8f5", 160, 60)]
y = -158
for color, w, h in layers:
box(-w / 2, y, w, h, color)
# 每層上面的奶油花邊
t.penup()
for x in range(int(-w / 2) + 10, int(w / 2), 20):
t.goto(x, y + h)
t.dot(16, "white")
y += h
# 蠟燭和火苗
candles = 5
for i in range(candles):
x = -60 + i * 120 / (candles - 1) if candles > 1 else 0
box(x - 5, y, 10, 50, random.choice(["tomato", "deepskyblue", "gold", "orchid"]))
t.penup()
t.goto(x, y + 62)
t.dot(16, "orange")
t.goto(x, y + 64)
t.dot(8, "yellow")
# 糖粒
t.penup()
for i in range(60):
t.goto(random.randint(-150, 150), random.randint(-150, 60))
t.dot(5, random.choice(["red", "green", "blue", "orange", "purple"]))
t.goto(0, 190)
t.color("#d6336c")
t.write("生日快樂!", align="center", font=("Arial", 36, "bold"))怎麼畫的
box(x, y, 寬, 高, 顏色) 畫一個填色的長方形,盤子、三層蛋糕、蠟燭都用它。
三層蛋糕寫在一個列表裡,每項是(顏色, 寬, 高);for color, w, h in layers 一層層往上畫,y += h 記住下一層從哪開始。
奶油花邊是沿著每層上邊每隔 20 點一個白色圓點;火苗是一大一小兩個圓點(橙色外、黃色裡)。
蠟燭的位置用 -60 + i * 120 / (candles - 1) 平均分開,根數改了也排得齊。
常見問題
蠟燭改到 12 根擠在一起?
蠟燭排在 120 寬的範圍裡。點「改一改」把 120 改大(比如 140),再把 -60 改成 -70。
怎麼寫上名字?
點「改一改」,把 write 裡的「生日快樂!」換成「小明 生日快樂!」再執行。
愛心表白兩段半圓拼成的心
玫瑰花一層層轉著畫的花瓣
跨年煙花會動的煙花:一幀一幀畫
聖誕樹彩燈、星星、雪,還有一句祝福