这次用Python的 pygame 库整一个动态彩色爱心,会跳动+颜色渐变,视觉效果更灵动~
import pygame
import math
import random
# 初始化pygame
pygame.init()
# 窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("动态彩色跳动爱心")
# 颜色渐变相关
def get_gradient_color(t):
"""根据时间t生成渐变RGB颜色"""
r = int(255 * abs(math.sin(t * 0.001)))
g = int(255 * abs(math.sin(t * 0.002)))
b = int(255 * abs(math.sin(t * 0.003)))
return (r, g, b)
# 爱心绘制函数
def draw_heart(surface, x, y, size, color):
"""绘制爱心形状"""
# 爱心参数方程
for angle in range(0, 360, 5):
rad = math.radians(angle)
# 爱心极坐标公式
r = size * (16 * math.sin(rad)**3)
heart_x = x + r * math.cos(rad)
heart_y = y - r * math.sin(rad)
pygame.draw.circle(surface, color, (int(heart_x), int(heart_y)), 2)
# 主循环变量
clock = pygame.time.Clock()
running = True
heart_size = 5
size_dir = 1 # 大小变化方向(1增大,-1减小)
time = 0
while running:
screen.fill((0, 0, 0)) # 黑色背景
time += 1
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 爱心大小跳动
heart_size += size_dir * 0.2
if heart_size > 8 or heart_size < 3:
size_dir *= -1
# 获取渐变颜色
current_color = get_gradient_color(time)
# 绘制爱心(居中)
draw_heart(screen, WIDTH//2, HEIGHT//2, heart_size, current_color)
# 更新屏幕
pygame.display.flip()
clock.tick(60)
pygame.quit()
运行效果:
- 爱心在窗口正中央持续跳动(大小循环变化)
- 颜色从红、绿、蓝、紫等色系平滑渐变,不会突兀
- 黑色背景衬托彩色爱心,视觉对比强烈
- 帧率稳定60,动画流畅无卡顿