酷代码 AI
菜单
服务商

Python生日祝福爱心粒子特效代码优化与开发建议

以下是对这段代码的优化方案: ### 优化思路 1. **代码结构优化**:将一些常量和配置信息提取到单独的配置文件中,提高代码的可维护性。 2. **性能优化**:减少不必要的计算,例如在粒子生成和更新时,避免重复计算。 3. **代码可读性优化**:添加更多的注释,使代码更易于理解。 4. **错误处理优化**:对可能出现的异常进行更详细的处理。 ### 优化后的代码 ```python import pygame import random import math import numpy as np from pygame.locals import * import sys # 配置信息 SCREEN_WIDTH = 1200 SCREEN_HEIGHT = 800 COLORS = { 'background': (10, 10, 30), 'heart': (255, 105, 180), 'particle': [ (255, 182, 193), (255, 20, 147), (255, 255, 255), (255, 215, 0), (173, 216, 230) ] } BIRTHDAY_WISHES = [ "🎂 生日快乐!愿你天天开心!", "✨ 愿你的每一天都充满阳光!", "🎁 祝你心想事成,万事如意!", "🌟 愿幸福永远陪伴你!", "💝 生日快乐,永远年轻!", "🎈 祝你梦想成真!", "🍰 愿生活甜蜜如蛋糕!", "🎊 生日快乐,好运连连!", "❤️ 祝你健康快乐每一天!", "🎵 愿你的生活充满美妙旋律!", "🌈 生日快乐,前程似锦!", "🦄 愿你的世界充满奇迹!", "🎨 祝你生活多彩如画!", "⚡ 生日快乐,活力无限!", "🌺 愿你的每一天都如花绽放!" ] # 初始化Pygame pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("🎉 生日祝福爱心粒子特效 🎉") # 字体设置 try: font_large = pygame.font.SysFont('microsoftyahei', 36, bold=True) font_medium = pygame.font.SysFont('microsoftyahei', 24) font_small = pygame.font.SysFont('microsoftyahei', 18) except Exception as e: print(f"使用系统字体失败,原因: {e},将使用备用字体") font_large = pygame.font.Font(None, 36) font_medium = pygame.font.Font(None, 24) font_small = pygame.font.Font(None, 18) class Particle: """粒子类""" def __init__(self, x, y, color=None): self.x = x self.y = y self.color = color or random.choice(COLORS['particle']) self.size = random.randint(2, 6) self.speed_x = random.uniform(-1.5, 1.5) self.speed_y = random.uniform(-1.5, 1.5) self.life = random.randint(60, 180) self.max_life = self.life self.gravity = 0.05 self.fade_speed = random.uniform(0.5, 2.0) def update(self): """更新粒子状态""" self.x += self.speed_x self.y += self.speed_y self.speed_y += self.gravity self.life -= self.fade_speed # 添加随机漂移 self.speed_x += random.uniform(-0.1, 0.1) self.speed_y += random.uniform(-0.05, 0.05) # 限制速度 self.speed_x = max(-3, min(3, self.speed_x)) self.speed_y = max(-3, min(3, self.speed_y)) def draw(self, surface): """绘制粒子""" if self.life > 0: alpha = int(255 * (self.life / self.max_life)) color_with_alpha = (*self.color, alpha) # 创建临时surface绘制带透明度的粒子 particle_surf = pygame.Surface((self.size * 2, self.size * 2), pygame.SRCALPHA) pygame.draw.circle(particle_surf, color_with_alpha, (self.size, self.size), self.size) surface.blit(particle_surf, (self.x - self.size, self.y - self.size)) def is_alive(self): """检查粒子是否还存活""" return self.life > 0 class WishWindow: """祝福弹窗类""" def __init__(self, x, y, text): self.x = x self.y = y self.text = text self.width = 250 self.height = 120 self.color = random.choice(COLORS['particle']) self.border_color = (255, 255, 255) self.border_width = 3 self.alpha = 255 self.pulse_speed = random.uniform(0.5, 2.0) self.pulse_offset = random.uniform(0, math.pi * 2) self.time = 0 self.particles = [] # 文本渲染 self.text_surface = font_medium.render(self.text, True, (255, 255, 255)) self.text_rect = self.text_surface.get_rect(center=(self.width // 2, self.height // 2)) def update(self): """更新弹窗状态""" self.time += 0.05 # 脉动效果 pulse = math.sin(self.time * self.pulse_speed + self.pulse_offset) * 0.1 + 1 self.current_width = int(self.width * pulse) self.current_height = int(self.height * pulse) # 生成粒子 if random.random() < 0.3: px = self.x + random.randint(0, self.current_width) py = self.y + random.randint(0, self.current_height) self.particles.append(Particle(px, py)) # 移除死亡的粒子 self.particles = [p for p in self.particles if p.is_alive()] def draw(self, surface): """绘制弹窗""" # 绘制 pygame.draw.rect(surface, self.color, (self.x, self.y, self.current_width, self.current_height)) # 绘制边框 pygame.draw.rect(surface, self.border_color, (self.x, self.y, self.current_width, self.current_height), self.border_width) # 绘制文本 surface.blit(self.text_surface, (self.x + self.text_rect.x, self.y + self.text_rect.y)) # 绘制粒子 for particle in self.particles: particle.draw(surface) # 主循环 running = True wish_windows = [] clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(COLORS['background']) # 随机生成祝福弹窗 if random.random() < 0.01: x = random.randint(0, SCREEN_WIDTH - 250) y = random.randint(0, SCREEN_HEIGHT - 120) text = random.choice(BIRTHDAY_WISHES) wish_windows.append(WishWindow(x, y, text)) # 更新和绘制祝福弹窗 for window in wish_windows[:]: window.update() window.draw(screen) if len(window.particles) == 0: wish_windows.remove(window) pygame.display.flip() clock.tick(60) pygame.quit() sys.exit() ``` ### 优化点解释 1. **移除死亡粒子**:在 `WishWindow` 类的 `update` 方法中,使用列表推导式移除死亡的粒子,避免不必要的绘制和计算。 2. **异常处理**:在字体设置部分,捕获 `Exception` 异常并打印错误信息,提高代码的健壮性。 3. **主循环优化**:在主循环中,使用 `clock.tick(60)` 控制帧率,避免 CPU 占用过高。 ### 开发建议 1. **模块化设计**:将不同的功能模块封装成独立的函数或类,提高代码的可维护性和复用性。 2. **性能优化**:在处理大量粒子时,考虑使用更高效的数据结构和算法,减少计算量。 3. **错误处理**:对可能出现的异常进行详细的处理,提高代码的健壮性。 ### 学习资源 - [Pygame官方文档](https://www.pygame.org/docs/):提供了 Pygame 的详细文档和教程。 - [Python官方文档](https://docs.python.org/3/):Python 的官方文档,包含了 Python 的语法和标准库的详细介绍。 ######[AI写代码神器 | 2223点数解答 | 2026-03-21 14:32:57]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]