下面是一个独特的 Python 爱心代码,通过多种方式展现爱心形状,结合了图形绘制、动态效果和数学之美。这个程序不仅展示了爱心的视觉效果,还融入了一些有趣的数学变换。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as patches
from matplotlib.colors import LinearSegmentedColormap
import random
import math
# 设置中文字体
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
class HeartVisualizer:
"""爱心可视化类,包含多种爱心展示方式"""
def __init__(self):
"""初始化爱心可视化器"""
self.fig = plt.figure(figsize=(12, 10))
self.colors = ['#FF5252', '#FF7043', '#EF5350', '#EC407A', '#D81B60']
self.heart_cmap = LinearSegmentedColormap.from_list('heart_cmap',
['#FFCDD2', '#EF5350', '#B71C1C'])
def classic_heart(self, ax, size=1, color='#FF5252', alpha=1.0, fill=True):
"""绘制经典爱心形状"""
t = np.linspace(0, 2*np.pi, 1000)
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
# 调整大小和位置
x = x * size
y = y * size
if fill:
ax.fill(x, y, color=color, alpha=alpha)
else:
ax.plot(x, y, color=color, alpha=alpha, linewidth=2)
return ax
def rotating_heart(self, ax, frame, size=1):
"""绘制旋转爱心"""
t = np.linspace(0, 2*np.pi, 1000)
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
# 旋转角度
angle = frame * np.pi / 180
rotation_matrix = np.array([
[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]
])
# 应用旋转
points = np.array([x, y]).T @ rotation_matrix
x_rot, y_rot = points.T
# 调整大小
x_rot = x_rot * size
y_rot = y_rot * size
ax.fill(x_rot, y_rot, color=random.choice(self.colors), alpha=0.8)
return ax
def heart_with_arrows(self, ax, size=1):
"""绘制带箭头的爱心"""
# 绘制爱心
self.classic_heart(ax, size=size, color='#FF5252', alpha=0.9)
# 绘制箭头
arrow_props = dict(facecolor='black', shrink=0.05, width=1.5, headwidth=8)
ax.annotate('', xy=(0, size*15), xytext=(0, size*22), arrowprops=arrow_props)
ax.annotate('', xy=(size*15, 0), xytext=(size*22, 0), arrowprops=arrow_props)
# 添加数学公式
ax.text(size*10, size*20, r'$x = 16\sin^3t$', fontsize=12, ha='center')
ax.text(size*20, size*10, r'$y = 13\cos t - 5\cos2t - 2\cos3t - \cos4t$',
fontsize=12, ha='center')
return ax
def pixel_heart(self, ax, size=20, density=1.5):
"""绘制像素风格爱心"""
heart_points = []
for x in range(-size, size+1):
for y in range(-size, size+1):
# 爱心方程的离散化
val = (x**2 + y**2 - 1)**3 - x**2 * y**3
if val <= 0:
# 添加一些随机性,使爱心边缘更自然
if random.random() < density:
heart_points.append((x, y))
# 绘制像素
colors = [random.choice(self.colors) for _ in heart_points]
x_vals, y_vals = zip(*heart_points)
ax.scatter(x_vals, y_vals, color=colors, s=50, alpha=0.9)
return ax
def fractal_heart(self, ax, depth=5, size=1):
"""绘制分形爱心"""
def draw_fractal_heart(x, y, size, depth):
if depth == 0:
# 基础爱心
t = np.linspace(0, 2*np.pi, 100)
heart_x = 16 * np.sin(t)**3 * size + x
heart_y = (13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)) * size + y
ax.fill(heart_x, heart_y, color=random.choice(self.colors), alpha=0.7)
else:
# 递归绘制更小的爱心
new_size = size / 2.5
draw_fractal_heart(x, y, new_size, depth-1)
draw_fractal_heart(x - size * 10, y + size * 5, new_size, depth-1)
draw_fractal_heart(x + size * 10, y + size * 5, new_size, depth-1)
draw_fractal_heart(x - size * 5, y - size * 10, new_size, depth-1)
draw_fractal_heart(x + size * 5, y - size * 10, new_size, depth-1)
draw_fractal_heart(0, 0, size, depth)
return ax
def heart_animation(self, frame):
"""爱心动画函数"""
self.fig.clear()
# 创建4x4网格
ax1 = self.fig.add_subplot(221)
ax2 = self.fig.add_subplot(222)
ax3 = self.fig.add_subplot(223)
ax4 = self.fig.add_subplot(224)
# 隐藏坐标轴
for ax in [ax1, ax2, ax3, ax4]:
ax.set_aspect('equal')
ax.axis('off')
# 绘制不同风格的爱心
self.classic_heart(ax1, size=0.8, color=plt.cm.jet(frame/100))
ax1.set_title('经典爱心曲线')
self.rotating_heart(ax2, frame, size=0.8)
ax2.set_title('旋转爱心')
self.pixel_heart(ax3, size=15, density=0.9 - (frame%20)/200)
ax3.set_title('像素风格爱心')
self.fractal_heart(ax4, depth=4, size=15)
ax4.set_title('分形爱心')
# 添加主标题
self.fig.suptitle('爱心的多种数学表达', fontsize=20, color='#D81B60')
return self.fig,
def run(self):
"""运行爱心动画"""
ani = FuncAnimation(self.fig, self.heart_animation, frames=180, interval=50, blit=True)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
visualizer = HeartVisualizer()
visualizer.run()
这个程序创建了一个 HeartVisualizer 类,包含多种展示爱心的方法:
经典爱心曲线:使用数学参数方程绘制标准爱心形状
旋转爱心:动态旋转的爱心效果
带箭头的爱心:展示爱心的数学公式
像素风格爱心:用离散点表示的爱心形状
分形爱心:递归生成的复杂爱心图案
程序通过动画循环展示这些不同形式的爱心,结合了色彩变化和动态效果。你可以直接运行这段代码,欣赏这些独特的爱心图形。
喜欢的盆友点个赞!