This repository has been archived on 2026-02-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Let_it_snow/main.py
2025-12-29 12:03:30 +08:00

103 lines
3.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pygame
import random
import sys
# 初始化Pygame新增音频初始化
pygame.init()
# 初始化音频混合器处理BGM播放
pygame.mixer.init()
# 1. 窗口设置
WIDTH, HEIGHT = 800, 600 # 窗口宽高
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("我期待的不是雪 而是有你的冬天")
# 2. 背景音乐播放(新增核心代码)
def play_bgm():
try:
# 加载背景音乐文件请确保snow_bgm.mp3和代码同目录
pygame.mixer.music.load("./我期待的不是雪.mp3")
# 设置音量0.0-1.00.5是50%音量,避免过大)
pygame.mixer.music.set_volume(0.5)
# 播放BGM参数-1表示无限循环0表示只播放1次
pygame.mixer.music.play(-1)
print("BGM播放成功")
except Exception as e:
# 捕获音频文件不存在/格式错误等异常,避免程序崩溃
print(f"BGM播放失败{e}")
print("请检查音频文件是否存在、格式是否为MP3/WAV且文件名正确")
# 调用BGM播放函数
play_bgm()
# 3. 雪花相关设置
SNOWFLAKE_COUNT = 150 # 雪花数量
snowflakes = []
# 初始化雪花列表
for _ in range(SNOWFLAKE_COUNT):
x = random.randint(0, WIDTH)
y = random.randint(-HEIGHT, 0)
size = random.randint(2, 5)
speed = random.uniform(1, 3)
snowflakes.append([x, y, size, speed])
# 4. 主循环设置
clock = pygame.time.Clock()
running = True
# 主游戏循环
while running:
clock.tick(60)
# 处理事件新增按ESC键可暂停/继续BGM
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
# 按ESC键切换BGM播放/暂停状态
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if pygame.mixer.music.get_busy():
pygame.mixer.music.pause()
print("BGM已暂停")
else:
pygame.mixer.music.unpause()
print("BGM已继续")
# 填充背景色
screen.fill((20, 20, 30))
# 更新并绘制雪花
for i in range(len(snowflakes)):
x, y, size, speed = snowflakes[i]
# 新增:雪花轻微左右摇摆,更真实
x += random.uniform(-0.15, 0.15)
snowflakes[i][0] = x
y += speed
snowflakes[i][1] = y
if y > HEIGHT:
snowflakes[i][0] = random.randint(0, WIDTH)
snowflakes[i][1] = random.randint(-20, -5)
# 绘制雪花(轻微透明,更逼真)
snow_surface = pygame.Surface((size*2, size*2), pygame.SRCALPHA)
pygame.draw.circle(snow_surface, (255, 255, 255, 200), (size, size), size)
screen.blit(snow_surface, (int(x-size), int(y-size)))
pygame.display.flip()
# 退出前停止BGM
pygame.mixer.music.stop()
pygame.quit()
sys.exit()
# 打包
# pip install pyinstaller
# pyinstaller -F -w main.py