用python写下雨代码,动态展示
时间: 2024-05-03 12:20:46 浏览: 155
可以使用Python的pygame库来实现下雨效果。以下是示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 屏幕的尺寸
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 雨滴的颜色
RAIN_COLOR = (200, 200, 255)
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 雨滴列表
raindrops = []
# 添加新雨滴的函数
def add_raindrop():
x = random.randint(0, SCREEN_WIDTH)
y = random.randint(-SCREEN_HEIGHT, 0)
velocity = random.randint(10, 20)
size = random.randint(1, 3)
raindrops.append({'x': x, 'y': y, 'velocity': velocity, 'size': size})
# 渲染雨滴的函数
def render_raindrops():
for raindrop in raindrops:
x = raindrop['x']
y = raindrop['y']
size = raindrop['size']
pygame.draw.line(screen, RAIN_COLOR, (x, y), (x, y + size))
# 移动雨滴的函数
def update_raindrops():
for raindrop in raindrops:
raindrop['y'] += raindrop['velocity']
if raindrop['y'] > SCREEN_HEIGHT:
raindrops.remove(raindrop)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 添加新雨滴
if random.randint(0, 50) == 0:
add_raindrop()
# 清屏
screen.fill((0, 0, 0))
# 渲染雨滴
render_raindrops()
# 移动雨滴
update_raindrops()
# 更新屏幕
pygame.display.flip()
# 退出pygame
pygame.quit()
```
这段代码会在屏幕上动态展示下雨的效果。你可以根据自己的需要调整参数,比如修改屏幕尺寸、调整雨滴的大小和速度等等。
阅读全文