Python流星雨特效代码
时间: 2023-12-05 17:40:15 浏览: 129
“流星雨的实现”程序代码
以下是Python实现流星雨特效的代码:
```python
import random
import pygame
# 初始化Pygame
pygame.init()
# 设置窗口大小
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 定义流星类
class Meteor:
def __init__(self, x, y, speed):
self.x = x
self.y = y
self.speed = speed
self.size = random.randint(1, 4)
def update(self):
self.y += self.speed
self.x += self.speed / 2
if self.y > height or self.x > width:
self.y = random.randint(-height, 0)
self.x = random.randint(0, width)
def draw(self):
pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.size, self.size))
# 初始化流星列表
meteors = []
for i in range(10):
x = random.randint(0, width)
y = random.randint(-height, 0)
speed = random.randint(5, 15)
meteor = Meteor(x, y, speed)
meteors.append(meteor)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 填充背景色
screen.fill((0, 0, 0))
# 更新流星位置
for meteor in meteors:
meteor.update()
meteor.draw()
# 刷新屏幕
pygame.display.flip()
```
阅读全文