当前位置: 欣欣网 > 码农

python下雪效果

2024-02-18码农

大家好!今天给你们带来了python pygame下雪效果。

安装pygame:

pip install pygame

完整代码:

importpygameimportrandom# 初始化pygamepygame.init()# 获取屏幕尺寸screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)pygame.display.set_caption("SnowAnimation")# 设置背景颜色为黑色background_color = (0, 0, 0)# 雪花列表snow_list = []# 初始化雪花:[x坐标, y坐标, x轴速度, y轴速度]fori in range(200):x = random.randrange(0, screen.get_width())y = random.randrange(0, screen.get_height())sx = random.randint(-1, 1)sy = random.randint(3, 6)snow_list.append([x,y, sx, sy])clock = pygame.time.Clock()# 游戏主循环done = Falsewhilenot done: # 消息事件循环,判断退出forevent in pygame.event.get():ifevent.type == pygame.QUIT:done = Trueelifevent.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:done = True # 显示背景颜色screen.fill(background_color) # 雪花列表循环fori in range(len(snow_list)): # 绘制雪花,颜色、位置、大小pygame.draw.circle(screen,(255, 255, 255), snow_list[i][:2], snow_list[i][3]-3) # 移动雪花位置(下一次循环起效)snow_list[i][0]+= snow_list[i][2]snow_list[i][1]+= snow_list[i][3] # 如果雪花落出屏幕,重设位置ifsnow_list[i][1] > screen.get_height():snow_list[i][1] = random.randrange(-50, -10)snow_list[i][0] = random.randrange(0, screen.get_width()) # 刷新屏幕pygame.display.flip()clock.tick(20)# 退出 pygame.quit()