关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520
先给出效果图:
源码如下:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕尺寸
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 设置雪花属性
snowflakes = []
for i in range(50):
x = random.randrange(0, width)
y = random.randrange(0, height)
speed = random.uniform(1, 3)
size = random.randint(3, 6) # 雪花大小参数
snowflakes.append([x, y, speed, size])
# 循环直到用户关闭窗口
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕颜色
screen.fill((200, 200, 200)) # (0, 0, 0)黑色;(200, 200, 200)阴天
# 绘制雪花
for flake in snowflakes:
pygame.draw.circle(screen, (255, 255, 255), (int(flake[0]), int(flake[1])), flake[3]) # 使用大小参数绘制雪花
flake[1] += flake[2] # 移动雪花
if flake[1] > height:
flake[1] = random.randrange(-50, -10)
flake[0] = random.randrange(0, width)
# 更新屏幕
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(30)
# 退出pygame
pygame.quit()
下面给出改进版
效果图:
使用一张背景图片(我这里文件名:snow_background.jpg),和代码文件放在同一目录下
源码如下:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕尺寸
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 加载背景图片
background = pygame.image.load('snow_background.jpg')
background = pygame.transform.scale(background, (width, height))
# 设置雪花属性
snowflakes = []
for i in range(50):
x = random.randrange(0, width)
y = random.randrange(0, height)
speed = random.uniform(1, 3)
size = random.randint(3, 6) # 雪花大小参数
snowflakes.append([x, y, speed, size])
# 循环直到用户关闭窗口
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充屏幕颜色
#screen.fill((200, 200, 200)) # (0, 0, 0)黑色;(200, 200, 200)阴天
# 绘制背景图片
screen.blit(background, (0, 0))
# 移动雪花并重新绘制
for flake in snowflakes:
pygame.draw.circle(screen, (255, 255, 255), (int(flake[0]), int(flake[1])), flake[3]) # 使用大小参数绘制雪花
flake[1] += flake[2] # 移动雪花
if flake[1] > height:
flake[1] = random.randrange(-50, -10)
flake[0] = random.randrange(0, width)
# 更新屏幕
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(30)
# 退出pygame
pygame.quit()
附:RGB 颜色表 https://www.codeeeee.com/color/rgb.html