月光与饼:Python 爱情月饼可视化
以下代码通过 Turtle 绘制动态月饼,融入「心跳」光效与爱情诗句,用代码解构「月饼团圆」与「爱情永恒」的关联,每一处细节都暗藏浪漫设计:
python
import turtle
import math
import time
# 核心配置:用柔和的暖色调模拟月光下的月饼
MOONCAKE_COLOR = "#F5D76E" # 月饼底色(香槟金)
FILL_COLOR = "#F8C471" # 填充色(暖橙金)
HEART_COLOR = "#E74C3C" # 爱心色(中国红)
TEXT_COLOR = "#8B4513" # 文字色(深棕木色)
def draw_heart(t, x, y, size):
"""绘制爱心:爱情的核心符号"""
t.penup()
t.goto(x, y)
t.pendown()
t.color(HEART_COLOR)
t.begin_fill()
# 爱心数学模型:基于参数方程的优雅曲线
for angle in range(0, 360, 2):
rad = math.radians(angle)
x_pos = size * 16 * (math.sin(rad) ** 3)
y_pos = size * (13 * math.cos(rad) - 5 * math.cos(2*rad) - 2 * math.cos(3*rad) - math.cos(4*rad))
t.goto(x + x_pos, y + y_pos)
t.end_fill()
def draw_mooncake(t, x, y, radius):
"""绘制月饼主体:团圆的象征"""
t.penup()
t.goto(x, y - radius)
t.pendown()
t.color(MOONCAKE_COLOR, FILL_COLOR)
t.begin_fill()
t.circle(radius) # 外圆:圆满的寓意
t.end_fill()
# 绘制月饼花纹:传统云纹简化版
t.penup()
t.goto(x, y)
t.setheading(0)
t.color(TEXT_COLOR)
t.pensize(2)
# 四组对称花纹:代表四季相伴
for _ in range(4):
t.pendown()
t.circle(radius * 0.6, 90) # 内弧
t.circle(radius * 0.1, 90) # 转折小弧
t.penup()
t.setheading(t.heading() + 90)
def heartbeat_effect(t, x, y, radius):
"""心跳光效:模拟爱情的悸动"""
for _ in range(3): # 三次心跳循环
# 第一次收缩:心动的紧张
t.penup()
t.goto(x, y - radius * 0.9)
t.pendown()
t.color(MOONCAKE_COLOR, FILL_COLOR + "99") # 半透明效果
t.begin_fill()
t.circle(radius * 0.9)
t.end_fill()
time.sleep(0.2)
# 第二次扩张:心动的雀跃
t.penup()
t.goto(x, y - radius * 1.1)
t.pendown()
t.color(MOONCAKE_COLOR, FILL_COLOR + "FF") # 不透明效果
t.begin_fill()
t.circle(radius * 1.1)
t.end_fill()
time.sleep(0.2)
# 恢复原状:归于平淡却持久的爱
t.penup()
t.goto(x, y - radius)
t.pendown()
t.color(MOONCAKE_COLOR, FILL_COLOR)
t.begin_fill()
t.circle(radius)
t.end_fill()
def write_love_text(t, x, y):
"""书写爱情诗句:赋予月饼情感内核"""
t.penup()
t.goto(x, y + 50)
t.pendown()
t.color(TEXT_COLOR)
t.write("但愿人长久", align="center", font=("SimHei", 16, "bold"))
t.penup()
t.goto(x, y + 20)
t.pendown()
t.write("千里共婵娟", align="center", font=("SimHei", 16, "bold"))
t.penup()
t.goto(x, y - 20)
t.pendown()
t.write("—— 致此生唯一的你", align="center", font=("SimHei", 12, "italic"))
# 主程序:串联所有浪漫元素
if __name__ == "__main__":
# 初始化画布:模拟夜空
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("#1A237E") # 深靛蓝:夜空底色
screen.title("月光下的爱情月饼")
# 初始化画笔
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0) # 最快绘制速度
# 绘制流程:层层递进的浪漫
1. 绘制月饼主体
draw_mooncake(pen, 0, 0, 150)
2. 心跳光效:赋予月饼"生命"
heartbeat_effect(pen, 0, 0, 150)
3. 绘制中心爱心:点明爱情主题
draw_heart(pen, 0, -20, 3)
4. 书写诗句:升华情感
write_love_text(pen, 0, -80)
# 保持窗口显示
turtle.done()
代码浪漫设计解析
1. 数学美学:爱心采用笛卡尔参数方程绘制,曲线自然流畅,避免生硬的几何拼接;
2. 动态隐喻:「心跳光效」模拟爱情中的悸动,收缩与扩张对应心动时的紧张与雀跃;
3. 文化融合:将苏轼《水调歌头》的经典诗句嵌入,让传统月饼承载现代爱情表达;
4. 色彩心理学:暖金色月饼象征团圆温暖,中国红爱心传递热烈情感,深靛蓝背景模拟中秋夜空,色彩搭配符合东方审美。