大家好!今天給你們帶來了python pygame下雪效果。
安裝pygame:
pip install pygame
完整程式碼:
importpygame
importrandom
# 初始化pygame
pygame.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 = False
whilenot done:
# 訊息事件迴圈,判斷結束
forevent in pygame.event.get():
ifevent.type == pygame.QUIT:
done = True
elifevent.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()