import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("樱花飘落")
# 定义颜色和字体
WHITE = (255, 255, 255)
PINK = (255, 192, 203)
FONT = pygame.font.Font(None, 36)
# 定义樱花类
class Sakura:
def __init__(self):
self.image = pygame.image.load("sakura.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WINDOW_WIDTH)
self.rect.y = random.randint(-WINDOW_HEIGHT, 0)
self.speed = random.randint(5, 15)
def move(self):
self.rect.y += self.speed
if self.rect.y > WINDOW_HEIGHT:
self.rect.x = random.randint(0, WINDOW_WIDTH)
self.rect.y = random.randint(-WINDOW_HEIGHT, 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
# 创建樱花列表
sakura_list = []
for i in range(50):
sakura = Sakura()
sakura_list.append(sakura)
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 绘制背景
window_surface.fill(WHITE)
# 绘制樱花
for sakura in sakura_list:
sakura.move()
sakura.draw(window_surface)
# 绘制标题
title_text = FONT.render("樱花飘落", True, PINK)
title_rect = title_text.get_rect()
title_rect.centerx = window_surface.get_rect().centerx
title_rect.y = 50
window_surface.blit(title_text, title_rect)
# 更新窗口
pygame.display.update()
需要pychrom代码下载pygame库