名人說:路漫漫其修遠兮,吾將上下而求索。—— 屈原《離騷》
創作者:Code_流蘇(CSDN)(一個喜歡古詩詞和編程的Coder😊)
專欄介紹:《Python星球日記》
目錄
- 一、項目簡介與效果展示
- 二、技術棧與核心概念
- 1. 主要技術棧
- 2. 核心概念解析
- 三、關鍵實現原理
- 1. 流星運動軌跡
- 2. 粒子系統實現
- 3. 中文字體顯示
- 四、完整代碼及分析
- 五、運行方法與操作指南
- 1. 環境準備
- 2. 運行程序
- 3. 交互操作
- 4. 性能說明
- 六、學習價值與擴展思路
- 1. 學習價值
- 2. 擴展思路
- 七、總結
歡迎大家來到Python星球日記的趣學篇,在趣學篇,我們將帶來很多有趣的適合初學者的項目,項目均由個人團隊開發及AI vide coding的輔助…
🌟 想要在電腦屏幕上重現那種令人心醉的流星雨美景嗎?今天我們就用Python從零開始,打造一個炫酷的流星雨動畫!不僅有逼真的物理效果,還能顯示中文字符,讓你在編程的同時感受浪漫的星空之美。
一、項目簡介與效果展示
這是一個基于Pygame開發的流星雨動畫項目,具有以下特效:
🌠 多彩流星:8種不同顏色的流星隨機生成,每顆都有獨特的軌跡
? 粒子尾跡:每個流星都帶有動態的粒子拖尾效果,增強視覺沖擊力
🌟 閃爍星空:150顆背景星星營造真實的夜空氛圍
🌌 漸變背景:深藍到黑色的自然漸變,模擬夜空色彩
💫 斜向軌跡:所有流星都以30-60度角自然斜向下運動
🎨 中文顯示:完美支持中文字體,顯示"斜向流星雨來啦!"等文字
預期效果:
實際效果:
整個程序運行流暢,達到60FPS的絲滑體驗,讓你仿佛置身于真實的流星雨之中!
二、技術棧與核心概念
1. 主要技術棧
- Pygame:Python游戲開發庫,負責圖形渲染和事件處理
- 數學庫(math):用于三角函數計算,實現精確的運動軌跡
- 隨機庫(random):生成隨機的流星屬性和位置
2. 核心概念解析
粒子系統:這是游戲特效中的經典概念。想象一下,每顆流星就像一個"粒子發射器",不斷產生小粒子形成美麗的尾跡。
Alpha混合:通過調整透明度實現漸變效果,讓流星尾跡從亮到暗自然過渡。
面向對象設計:將流星、星星、特殊流星都封裝成獨立的類,代碼結構清晰易維護。
三、關鍵實現原理
1. 流星運動軌跡
真實的流星雨并不是垂直下落,而是以一定角度斜向劃過天空。我們使用三角函數來實現這種自然的運動效果:
# 設置流星的斜向運動
angle = random.uniform(math.radians(30), math.radians(60)) # 30-60度角
speed = random.uniform(12, 20)
self.speed_x = -speed * math.cos(angle) # 水平分量
self.speed_y = speed * math.sin(angle) # 垂直分量
這樣計算出來的速度分量,讓每顆流星都能以不同但合理的角度斜向飛行,營造出逼真的流星雨效果。
2. 粒子系統實現
每顆流星都會不斷產生小粒子,形成絢爛的尾跡:
# 為流星添加尾跡粒子
for i in range(4):particle = {'x': self.x + random.randint(-8, 8),'y': self.y + random.randint(-8, 8), 'life': random.randint(25, 40), # 粒子生命周期'color': self.color,'size': random.randint(1, 4)}self.tail_particles.append(particle)
每個粒子都有自己的生命周期,隨著時間推移逐漸變暗消失,這就是我們看到的流星尾跡漸變效果。
3. 中文字體顯示
程序智能適配多種操作系統的中文字體:
font_paths = ["C:/Windows/Fonts/simhei.ttf", # Windows黑體"C:/Windows/Fonts/msyh.ttc", # 微軟雅黑 "/System/Library/Fonts/PingFang.ttc", # macOS蘋方"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf" # Linux
]
程序會自動嘗試加載這些字體,確保在不同系統上都能正確顯示中文。
四、完整代碼及分析
import pygame
import random
import math
import sys# 初始化pygame
pygame.init()# 設置屏幕尺寸
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("炫酷斜向流星雨動畫 - 按ESC退出")# 顏色定義
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (100, 150, 255)
CYAN = (0, 255, 255)
YELLOW = (255, 255, 0)
PINK = (255, 100, 150)
PURPLE = (150, 100, 255)
GREEN = (100, 255, 150)
ORANGE = (255, 150, 50)class Meteor:def __init__(self):self.reset()def reset(self):self.x = random.randint(-100, SCREEN_WIDTH + 200)self.y = random.randint(-800, -50)# 設置更明顯的斜向下運動 - 角度大約在30-60度之間angle = random.uniform(math.radians(30), math.radians(60)) # 30-60度角speed = random.uniform(12, 20) # 總速度self.speed_x = -speed * math.cos(angle) # 向左下self.speed_y = speed * math.sin(angle) # 向下self.length = random.randint(60, 200)self.width = random.randint(2, 6)self.color = random.choice([BLUE, CYAN, WHITE, YELLOW, PINK, PURPLE, GREEN, ORANGE])self.tail_particles = []self.life = 255def update(self):# 更新位置self.x += self.speed_xself.y += self.speed_y# 添加尾跡粒子for i in range(4):particle = {'x': self.x + random.randint(-8, 8),'y': self.y + random.randint(-8, 8),'life': random.randint(25, 40),'color': self.color,'size': random.randint(1, 4)}self.tail_particles.append(particle)# 更新尾跡粒子for particle in self.tail_particles[:]:particle['life'] -= 1.5particle['x'] += random.uniform(-0.5, 0.5)particle['y'] += random.uniform(-0.5, 0.5)if particle['life'] <= 0:self.tail_particles.remove(particle)# 如果流星離開屏幕,重置位置if self.y > SCREEN_HEIGHT + 100 or self.x < -200:self.reset()def draw(self, surface):# 繪制尾跡粒子for particle in self.tail_particles:alpha = max(0, particle['life'] / 40.0)size = max(1, int(particle['size'] * alpha))color = [min(255, int(c * alpha * 1.2)) for c in particle['color']]# 創建帶透明度的粒子表面particle_surface = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)pygame.draw.circle(particle_surface, (*color, int(255 * alpha)), (size, size), size)surface.blit(particle_surface, (int(particle['x'] - size), int(particle['y'] - size)))# 繪制流星主體 - 創建沿運動方向的漸變效果segments = min(self.length, 50)for i in range(segments):progress = i / segmentsalpha = 1 - progress# 沿著流星運動方向繪制尾跡current_x = self.x - (self.speed_x * progress * 3) # 調整尾跡長度current_y = self.y - (self.speed_y * progress * 3)if 0 <= current_x <= SCREEN_WIDTH and 0 <= current_y <= SCREEN_HEIGHT:# 計算當前片段的顏色和大小color = [min(255, int(c * alpha * 1.3)) for c in self.color]width = max(1, int(self.width * alpha))# 創建帶透明度的流星片段meteor_surface = pygame.Surface((width * 2, width * 2), pygame.SRCALPHA)pygame.draw.circle(meteor_surface, (*color, int(255 * alpha)), (width, width), width)surface.blit(meteor_surface, (int(current_x - width), int(current_y - width)))class Star:def __init__(self):self.x = random.randint(0, SCREEN_WIDTH)self.y = random.randint(0, SCREEN_HEIGHT)self.brightness = random.randint(80, 255)self.twinkle_speed = random.uniform(0.02, 0.08)self.twinkle_phase = random.uniform(0, 2 * math.pi)self.size = random.choice([1, 1, 1, 2]) # 大部分是小星星def update(self):self.twinkle_phase += self.twinkle_speeddef draw(self, surface):current_brightness = int(self.brightness * (0.3 + 0.7 * abs(math.sin(self.twinkle_phase))))color = (current_brightness, current_brightness, min(255, current_brightness + 20))pygame.draw.circle(surface, color, (int(self.x), int(self.y)), self.size)class ShootingStar:def __init__(self):self.reset()def reset(self):self.x = random.randint(-100, SCREEN_WIDTH + 100)self.y = random.randint(-300, SCREEN_HEIGHT//3)# 讓特殊流星也是斜向下運動,但角度稍有不同self.angle = random.uniform(math.radians(25), math.radians(65)) # 25-65度角self.speed = random.randint(18, 28)self.length = random.randint(100, 150)self.life = random.randint(60, 100)self.max_life = self.lifeself.color = random.choice([WHITE, YELLOW, CYAN])def update(self):# 按照設定角度斜向下移動self.x += -self.speed * math.cos(self.angle) # 向左self.y += self.speed * math.sin(self.angle) # 向下self.life -= 1if self.life <= 0 or self.x < -100 or self.x > SCREEN_WIDTH + 100 or self.y > SCREEN_HEIGHT + 100:self.reset()def draw(self, surface):alpha = self.life / self.max_lifefor i in range(20):progress = i / 20# 沿著運動方向繪制尾跡trail_x = self.x + self.speed * math.cos(self.angle) * progress * self.length / 20trail_y = self.y - self.speed * math.sin(self.angle) * progress * self.length / 20trail_alpha = alpha * (1 - progress)if -50 <= trail_x <= SCREEN_WIDTH + 50 and -50 <= trail_y <= SCREEN_HEIGHT + 50:color = [int(c * trail_alpha) for c in self.color]size = max(1, int(3 * trail_alpha))trail_surface = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)pygame.draw.circle(trail_surface, (*color, int(255 * trail_alpha)), (size, size), size)surface.blit(trail_surface, (int(trail_x - size), int(trail_y - size)))def create_gradient_background():background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))for y in range(SCREEN_HEIGHT):# 創建從深藍到黑色的漸變progress = y / SCREEN_HEIGHTr = int(5 * (1 - progress))g = int(10 * (1 - progress))b = int(30 * (1 - progress))color = (r, g, b)pygame.draw.line(background, color, (0, y), (SCREEN_WIDTH, y))return backgrounddef main():clock = pygame.time.Clock()# 創建流星列表meteors = [Meteor() for _ in range(20)]# 創建星星背景stars = [Star() for _ in range(150)]# 創建特殊流星shooting_stars = [ShootingStar() for _ in range(3)]# 設置中文字體 - 嘗試多種字體路徑font = Nonefont_paths = ["simhei.ttf","C:/Windows/Fonts/simhei.ttf","C:/Windows/Fonts/msyh.ttc","C:/Windows/Fonts/simsun.ttc","/System/Library/Fonts/PingFang.ttc", # macOS"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf", # Linux]for font_path in font_paths:try:font = pygame.font.Font(font_path, 60)breakexcept:continueif font is None:# 如果找不到中文字體,使用系統默認字體font = pygame.font.Font(None, 60)# 創建多行文字texts = ["流星雨來啦!", "許個愿吧~"]text_surfaces = []for i, text in enumerate(texts):try:text_surface = font.render(text, True, WHITE)except:# 如果渲染中文失敗,使用英文text_surface = font.render("Meteor Shower!" if i == 0 else "Make a wish~", True, WHITE)text_surfaces.append(text_surface)# 創建漸變背景background = create_gradient_background()running = Trueframe_count = 0print("流星雨動畫已啟動!")print("操作說明:")print("- 按 ESC 鍵退出")print("- 按空格鍵添加特殊斜向流星")print("- 享受這場飛舞的絢爛流星雨吧!")while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_ESCAPE:running = Falseelif event.key == pygame.K_SPACE:# 添加特殊流星 - 也是斜向下運動special_meteor = Meteor()special_meteor.length = 300special_meteor.width = 10special_meteor.color = WHITE# 重新設置運動方向確保是斜向下angle = random.uniform(math.radians(35), math.radians(55))speed = random.uniform(15, 25)special_meteor.speed_x = -speed * math.cos(angle)special_meteor.speed_y = speed * math.sin(angle)meteors.append(special_meteor)frame_count += 1# 繪制背景screen.blit(background, (0, 0))# 更新和繪制星星for star in stars:star.update()star.draw(screen)# 更新和繪制特殊流星for shooting_star in shooting_stars:shooting_star.update()shooting_star.draw(screen)# 更新和繪制普通流星for meteor in meteors:meteor.update()meteor.draw(screen)# 繪制標題文字,添加浮動和閃爍效果for i, text_surface in enumerate(text_surfaces):alpha = int(200 + 55 * math.sin(frame_count * 0.05 + i))y_offset = int(10 * math.sin(frame_count * 0.03 + i))text_with_alpha = text_surface.copy()text_with_alpha.set_alpha(alpha)text_rect = text_surface.get_rect(center=(SCREEN_WIDTH // 2, 120 + i * 80 + y_offset))screen.blit(text_with_alpha, text_rect)# 定期添加隨機流星if frame_count % 90 == 0: # 每1.5秒new_meteor = Meteor()meteors.append(new_meteor)# 偶爾添加超級流星if frame_count % 300 == 0: # 每5秒super_meteor = Meteor()super_meteor.length = 400super_meteor.width = 12super_meteor.color = random.choice([WHITE, YELLOW, CYAN])# 確保超級流星也是斜向下運動angle = random.uniform(math.radians(40), math.radians(50))speed = random.uniform(18, 25)super_meteor.speed_x = -speed * math.cos(angle)super_meteor.speed_y = speed * math.sin(angle)meteors.append(super_meteor)# 限制流星數量以保持性能if len(meteors) > 35:meteors.pop(0)# 添加一些隨機的星星if random.randint(1, 100) < 2:stars.append(Star())if len(stars) > 200:stars.pop(0)pygame.display.flip()clock.tick(60) # 60 FPSpygame.quit()sys.exit()if __name__ == "__main__":main()
整個項目采用面向對象的設計模式,主要包含以下幾個類:
Meteor
類:普通流星
reset()
:重置流星位置和屬性update()
:更新位置和粒子效果draw()
:繪制流星和尾跡
Star
類:背景星星
- 實現閃爍效果,營造夜空氛圍
ShootingStar
類:特殊流星
- 更大更亮,出現頻率較低
主程序循環:
- 事件處理(鍵盤輸入)
- 更新所有對象狀態
- 繪制所有圖形元素
- 控制幀率(60FPS)
五、運行方法與操作指南
1. 環境準備
# 安裝Pygame庫
pip install pygame
2. 運行程序
python meteor_shower.py
3. 交互操作
- ESC鍵:退出程序
- 空格鍵:手動添加一顆特殊流星
- 程序會自動生成各種流星效果,無需其他操作
4. 性能說明
- 支持1200×800分辨率
- 穩定60FPS運行
- 自動優化粒子數量,保證流暢性
六、學習價值與擴展思路
1. 學習價值
這個項目非常適合Python初學者,能夠學習到:
- Pygame基礎:圖形繪制、事件處理、游戲循環
- 數學應用:三角函數在編程中的實際運用
- 面向對象編程:類的設計和使用
- 算法優化:如何平衡視覺效果與性能
2. 擴展思路
想要讓你的流星雨更加炫酷?可以嘗試這些擴展:
🎵 音效系統:添加背景音樂和流星劃過的音效
🎮 交互玩法:讓用戶點擊流星獲得分數
🌈 更多特效:爆炸效果、彗星、UFO等
📱 移動適配:改造成手機應用
🤖 AI元素:讓流星根據音樂節拍變化
七、總結
通過這個流星雨項目,我們不僅創造了一個美麗的視覺效果,更重要的是學會了如何將數學知識與編程技巧相結合。從簡單的三角函數到復雜的粒子系統,每一行代碼都在為最終的視覺盛宴貢獻力量。
編程的魅力就在于此——我們可以用代碼重現自然之美,用算法詮釋浪漫情懷。無論你是編程新手還是資深開發者,都能從這樣的項目中獲得樂趣和成長。
快來運行這個程序,在你的屏幕上點亮一場專屬的數字流星雨吧!?
💡 小貼士:如果你對這個項目感興趣,建議動手實踐一下。編程最好的學習方式就是邊寫邊學,在調試和優化的過程中,你會發現更多有趣的細節和改進空間!
讓我們一起用代碼讓世界變得更有趣!🎉
創作者:Code_流蘇(CSDN)(一個喜歡古詩詞和編程的Coder😊)