正值武汉冰封之日,本人被困在实验室,百无聊赖之际,试一下pygame库的使用。
第一步:安装pygame库
在终端输入:
pip install pygame
第二步:复制下列代码
import pygame
import random
import sys
# 初始化pygame
pygame.init()
# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置标题
pygame.display.set_caption('雪花飘落')
# 定义雪花列表
snowflakes = [{
'x': random.randrange(0, screen_width),
'y': random.randrange(0, screen_height),
'size': random.randint(2, 5)
} for _ in range(200)]
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 游戏主循环
running = True
while running:
# 检查事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕
screen.fill(BLACK)
# 更新雪花位置
for snowflake in snowflakes:
pygame.draw.circle(screen, WHITE, (snowflake['x'], snowflake['y']), snowflake['size'])
snowflake['y'] += snowflake['size'] * 0.5
if snowflake['y'] > screen_height:
snowflake['x'] = random.randrange(0, screen_width)
snowflake['y'] = -10
# 更新屏幕显示
pygame.display.flip()
# 60帧每秒
pygame.time.Clock().tick(60)
# 退出pygame
pygame.quit()
sys.exit()
第三步:运行并观察结果