Kodewick
开始学 →

Python 生日蛋糕

三层蛋糕、奶油花边、点着的蜡烛和「生日快乐」。蜡烛根数改成寿星的岁数,存图发过去。

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 里的「生日快乐!」换成「小明 生日快乐!」再运行。

换个样子