怎么使用python写一个有意思的爱心代码呢???

53 阅读1分钟

首先不会也代码也没事,可以使用AI工具,我用的是豆包 告诉他,帮我写一条可以生成动态爱心的代码 import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import time from matplotlib.colors import hsv_to_rgb # 确保中文显示 plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"] plt.rcParams['axes.unicode_minus'] = False # 创建图形 fig, ax = plt.subplots(figsize=(8, 6)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1) ax.set_aspect('equal') ax.axis('off') # 爱心参数方程 def heart(t, scale=1.0): x = 16 * np.sin(t)**3 * scale y = (13 * np.cos(t) - 5 * np.cos(2t) - 2 * np.cos(3t) - np.cos(4t)) * scale return x, y t = np.linspace(0, 2np.pi, 1000) x, y = heart(t) line, = ax.plot(x, y, color='red', linewidth=2) fill = ax.fill(x, y, color='pink', alpha=0.5)[0] # 粒子初始化(修正解包错误) num_particles = 50 particles_x = np.random.uniform(-20, 20, num_particles) particles_y = np.random.uniform(-15, 25, num_particles) particles_size = np.random.uniform(2, 8, num_particles) particles = ax.scatter(particles_x, particles_y, s=particles_size, color='red', alpha=0.6) # 去掉多余的解包 ax.set_xlim(-25, 25) ax.set_ylim(-20, 30) # 动画更新函数 def update(frame): progress = frame / 100 # 大小变化 if progress < 0.3: scale = 0.5 + progress * 1.5 elif progress < 0.7: scale = 1.0 + np.sin(progress * 10) * 0.1 else: scale = 1.0 x_new, y_new = heart(t, scale) line.set_data(x_new, y_new) fill.set_xy(np.column_stack([x_new, y_new])) # 颜色渐变 hue = 0.9 - progress * 0.3 saturation = 0.8 + np.sin(progress * 5) * 0.1 rgb = hsv_to_rgb((hue, saturation, 0.9)) line.set_color(rgb) fill.set_color(hsv_to_rgb((hue + 0.05, saturation - 0.1, 0.9))) fill.set_alpha(0.5 + np.sin(progress * 3) * 0.2) # 粒子动画 global particles_x, particles_y center_x, center_y = 0, 5 particles_x += (center_x - particles_x) * 0.03 particles_y += (center_y - particles_y) * 0.03 new_sizes = particles_size * (1 + np.sin(progress * 5 + np.arange(num_particles)*0.5)*0.3) particles.set_offsets(np.column_stack([particles_x, particles_y])) particles.set_sizes(new_sizes) # 文字特效 if progress > 0.5: ax.set_title("爱 ❤️", fontsize=20 + np.sin(progress * 10)*2, color=rgb) else: ax.set_title("") return line, fill, particles # 创建动画(100帧,每帧50ms,共5秒动画) ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True) # 显示动画并阻塞窗口 plt.show(block=True) # 动画窗口关闭后停留3秒 print("动画已结束,将停留3秒...") time.sleep(3)

这是代码

image.png

这是生成的效果,实际是动态的,大家可以自己去尝试一下