pygame實現(xiàn)煙雨蒙蒙下彩虹雨
學習了一天的深度學習,略有疲憊,我們用pygame搞個小游戲放松放松吧。今天我們的游戲主體是煙雨蒙蒙下彩虹雨,仿佛置身江南水鄉(xiāng)。
游戲描述
我們希望看到江南水鄉(xiāng)下起彩虹雨。這里背景是江南水鄉(xiāng),煙雨蒙蒙,雨滴顏色五顏六色,大小不一。
解決思路
煙雨蒙蒙彩虹雨的意思很明確,有幾個主要元素,那就是煙雨蒙蒙,彩虹雨滴,下雨幾個元素和動作。那么,基本思路如下
1.找一張江南水鄉(xiāng)煙雨蒙蒙的圖片作為背景
2.用圓圈代表雨滴,并把圓圈的大小,顏色進行隨機設(shè)置,出現(xiàn)五彩斑斕的效果。
3.下雨,即雨滴從上而下持續(xù)不斷的落下,這就需要pygame里把圓圈放在不同的坐標下繪制出來。
代碼實現(xiàn)
具體的實現(xiàn)代碼如下:
import pygame
import random
pygame.init()
#加載圖片
pic=pygame.image.load('raining.jpg')
#獲取圖片的長寬
screen_width=pic.get_width()
screen_height=pic.get_height()
#根據(jù)圖片大小來設(shè)置屏幕大小
screen=pygame.display.set_mode([screen_width,screen_height])
#設(shè)置彩虹雨的雨滴個數(shù),顏色,位置,大小,落下的速度
numbers=50
colors=[0]*numbers
location_x=[0]*numbers
location_y=[0]*numbers
sizes=[0]*numbers
speed=[0]*numbers
#初始化彩虹雨滴
for i in range(numbers):
colors[i]=(random.randint(0,255),random.randint(0,255),random.randint(0,255))
location_x[i]=random.randint(0,screen_width)
location_y[i]=-random.randint(0,screen_height)
sizes[i]=random.randint(5,20)
speed[i]=random.randint(1,5)
keep_going=True
#用Clock實現(xiàn)來控制動畫的速度
timer=pygame.time.Clock()
while keep_going:
for event in pygame.event.get(): #監(jiān)聽事件
if event.type==pygame.QUIT:
keep_going=False
#把圖片繪制到屏幕
screen.blit(pic,(0,0))
for i in range(numbers):
pygame.draw.circle(screen,colors[i],(location_x[i],location_y[i]),sizes[i]) #讓雨滴畫在屏幕上
location_y[i]=location_y[i]+speed[i] #雨滴落下,y軸方向
if location_y[i]>screen_height: #如果雨滴落到看不見,即超出屏幕的高度
location_y[i]-=screen_height #重新設(shè)置雨滴的參數(shù)
location_x[i]=random.randint(0,screen_width)
speed[i] = random.randint(1, 5)
timer.tick(100)# timer每秒鐘滴答100次,因此幀率為100fps
pygame.display.update() #刷新屏幕
pygame.quit()
效果展示
運行可以看到下圖,還是有點那個意思的,靜靜地看著五彩斑斕的雨滴落下,一身的疲憊也減輕了不少。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python client使用http post 到server端的代碼
python client使用 http post 到server端的代碼,供大家學習參考2013-02-02
由Python運算π的值深入Python中科學計算的實現(xiàn)
這篇文章主要介紹了由Python運算π的值深入Python中科學計算的實現(xiàn),由簡單的計算發(fā)散出各種算法的講解,需要的朋友可以參考下2015-04-04
Python基礎(chǔ)之python循環(huán)控制語句break/continue詳解
Python中出現(xiàn)"No?module?named?'requests'"
在python下使用tensorflow判斷是否存在文件夾的實例

