pygame學習筆記(1):矩形、圓型畫圖執行個體

來源:互聯網
上載者:User
pygame是一個設計用來開發遊戲的python模組,其實說白了和time、os、sys都是一樣的東東。今天開始正式學習pygame,下載地址:www.pygame.org。下載後安裝完成即可,在pygame的學習中,我使用了spe編輯器,感覺還不錯。

1、pygame視窗

pygame繪製圖形前,首先需要建立一個視窗,說來很簡單,請看下面的代碼,怎麼樣,是不是很簡單。
複製代碼 代碼如下:


import pygame #這句不用注釋了吧,呵呵
pygame.init() #模組初始化,任何pygame程式均需要執行此句

screencaption=pygame.display.set_caption('hello world')#定義視窗的標題為'hello world'
screen=pygame.display.set_mode([640,480]) #定義視窗大小為640*480
screen.fill([255,255,255])#用白色填充視窗


2、視窗退出

pygame有一個事件迴圈,不斷檢查使用者在做什麼。事件迴圈中,如何讓迴圈中斷下來(pygame形成的視窗中右邊的插號在未定義前是不起作用的),常用的代碼如下:
複製代碼 代碼如下:


while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()


3、pygame中的顏色

在screen.fill([255,255,255])這一語句中,已經看出,pygame使用的是RGB系統。純綠色用[0,255,0],純藍色用[0,0,255],純紅色用[255,0,0]。如果不使用RGB記法,pygame還提供了一個命名顏色列表,也可以直接使用這些命名顏色。定義好的顏色句有600多個,可以在colordict.py檔案中查看具體名稱。使用命名列表時,首先要在程式最前面匯入THECOLORS。

from pygame.color import THECOLORS
然後使用某個命名顏色:
複製代碼 代碼如下:


pygame.draw.circle(screen,THECOLORS["red"],[100,100],30,0)


4、圓形

pygame.draw.circle()用來畫圓形,具體包括五個參數:(1)畫圓的表面,在本例中用screen建立了一個視窗,所以是畫在screen表面上。(2)用什麼顏色來畫,如用紅色[255,0,0]。(3)在什麼位置畫,[top,left]。(4)直徑。(5)線寬,其中0表示完成填充。
複製代碼 代碼如下:


pygame.draw.circle(screen,[255,0,0],[100,100],30,0)


5、矩形
pygame.draw.rect()用來建立一個矩形。Rect(left,top,width,height)用來定義位置和寬高,具體代碼如下:
複製代碼 代碼如下:


pygame.draw.rect(screen,[255,0,0],[250,150,300,200],0)


也可以用下面的定義方法
複製代碼 代碼如下:


rect_list=[250,150,300,200]
pygame.draw.rect(screen,[255,0,0],rect_list,0)


或者
複製代碼 代碼如下:


my_rect=pygame.Rect(250,150,300,200)
pygame.draw.rect(screen,[255,0,0],my_rect,0)


6、執行個體

利用random模組隨機產生大小和位置在表面上繪畫,具體代碼如下:

複製代碼 代碼如下:


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()


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.