pygame是一個設(shè)計用來開發(fā)游戲的python模塊,其實(shí)說白了和time、os、sys都是一樣的東東。今天開始正式學(xué)習(xí)pygame,下載地址:。下載后安裝完成即可,在pygame的學(xué)習(xí)中,我使用了spe編輯器,感覺還不錯。
1、pygame窗口
pygame繪制圖形前,首先需要建立一個窗口,說來很簡單,請看下面的代碼,怎么樣,是不是很簡單。
復(fù)制代碼 代碼如下:
import pygame #這句不用注釋了吧,呵呵
pygame.init() #模塊初始化,任何pygame程序均需要執(zhí)行此句
screencaption=pygame.display.set_caption('hello world')#定義窗口的標(biāo)題為'hello world'
screen=pygame.display.set_mode([640,480]) #定義窗口大小為640*480
screen.fill([255,255,255])#用白色填充窗口
pygame有一個事件循環(huán),不斷檢查用戶在做什么。事件循環(huán)中,如何讓循環(huán)中斷下來(pygame形成的窗口中右邊的插號在未定義前是不起作用的),常用的代碼如下:
復(fù)制代碼 代碼如下:
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
在screen.fill([255,255,255])這一語句中,已經(jīng)看出,pygame使用的是RGB系統(tǒng)。純綠色用[0,255,0],純藍(lán)色用[0,0,255],純紅色用[255,0,0]。如果不使用RGB記法,pygame還提供了一個命名顏色列表,也可以直接使用這些命名顏色。定義好的顏色句有600多個,可以在colordict.py文件中查看具體名稱。使用命名列表時,首先要在程序最前面導(dǎo)入THECOLORS。
from pygame.color import THECOLORS
然后使用某個命名顏色:
復(fù)制代碼 代碼如下:
pygame.draw.circle(screen,THECOLORS["red"],[100,100],30,0)
pygame.draw.circle()用來畫圓形,具體包括五個參數(shù):(1)畫圓的表面,在本例中用screen創(chuàng)建了一個窗口,所以是畫在screen表面上。(2)用什么顏色來畫,如用紅色[255,0,0]。(3)在什么位置畫,[top,left]。(4)直徑。(5)線寬,其中0表示完成填充。
復(fù)制代碼 代碼如下:
pygame.draw.circle(screen,[255,0,0],[100,100],30,0)
復(fù)制代碼 代碼如下:
pygame.draw.rect(screen,[255,0,0],[250,150,300,200],0)
復(fù)制代碼 代碼如下:
rect_list=[250,150,300,200]
pygame.draw.rect(screen,[255,0,0],rect_list,0)
復(fù)制代碼 代碼如下:
my_rect=pygame.Rect(250,150,300,200)
pygame.draw.rect(screen,[255,0,0],my_rect,0)
利用random模塊隨機(jī)生成大小和位置在表面上繪畫,具體代碼如下:
復(fù)制代碼 代碼如下:
import pygame,sys
import time
import random
pygame.init()
screencaption=pygame.display.set_caption('hello world')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
for i in range(10):
zhijing=random.randint(0,100)
width=random.randint(0,255)
height=random.randint(0,100)
top=random.randint(0,400)
left=random.randint(0,500)
pygame.draw.circle(screen,[0,0,0],[top,left],zhijing,1)
pygame.draw.rect(screen,[255,0,0],[left,top,width,height],3)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
效果圖:
新聞熱點(diǎn)
疑難解答
圖片精選