Python爱心代码实现(基础图形版)
import turtle
# 初始化画布和画笔
heart = turtle.Turtle()
heart.speed(5) # 中速绘制
heart.color('red', 'pink') # 边框红色,填充粉色
heart.begin_fill() # 开始填充
# 绘制爱心轮廓
heart.left(140)
heart.forward(113)
for i in range(200): # 绘制右侧曲线
heart.right(1)
heart.forward(1)
heart.left(120)
for i in range(200): # 绘制左侧曲线
heart.right(1)
heart.forward(1)
heart.forward(113)
heart.end_fill() # 结束填充
turtle.done() # 保持窗口显示
动态爱心升级版
import turtle
import math
def draw_heart(size):
t.penup()
t.goto(0, -size*1.1)
t.pendown()
angle = 0
t.begin_fill()
while angle <= 2 * math.pi:
x = 16 * (math.sin(angle) ** 3)
y = 13 * math.cos(angle) - 5 * math.cos(2*angle) - 2 * math.cos(3*angle) - math.cos(4*angle)
t.goto(x * size, y * size)
angle += 0.1
t.end_fill()
t = turtle.Turtle()
t.speed(0)
t.color('red', 'pink')
# 实现心跳效果
for i in range(30):
t.clear()
size = 10 + 2 * math.sin(i/2) # 动态调整大小
draw_heart(size)
turtle.update()
turtle.delay(50)
turtle.mainloop()
控制台字符爱心版
heart = '''
❤️ ❤️ ❤️
❤️ ❤️
❤️ ❤️
❤️ ❤️
❤️ ❤️
❤️
'''
for line in heart.split('\n'):
print(line.center(50))
3D旋转爱心(需要matplotlib)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
theta = np.linspace(0, 2*np.pi, 100)
x = 16 * np.sin(theta)**3
y = 13 * np.cos(theta) - 5 * np.cos(2*theta) - 2 * np.cos(3*theta) - np.cos(4*theta)
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111, projection='3d')
for angle in range(0, 360, 5):
ax.cla()
z = np.linspace(0, 1, len(x))
ax.plot(x, y, z, color='red', linewidth=4)
ax.plot(x, y, -z, color='red', linewidth=4)
ax.view_init(30, angle)
plt.draw()
plt.pause(0.05)
plt.show()
注意:3D版本需要安装matplotlib库(`pip install matplotlib`)