最近很火一些簡單圖形構成的小遊戲,這裏介紹一些繪製圖形的函數。函數
rect(Surface,color,Rect,width=0)
第一個參數指定矩形繪製到哪一個Surface對象上spa
第二個參數指定顏色code
第三個參數指定矩形的範圍(left,top,width,height)對象
第四個參數指定矩形邊框的大小(0表示填充矩形)blog
例如繪製三個矩形:遊戲
pygame.draw.rect(screen, BLACK, (50, 50, 150, 50), 0) pygame.draw.rect(screen, BLACK, (250, 50, 150, 50), 1) pygame.draw.rect(screen, BLACK, (450, 50, 150, 50), 10)
polygon(Surface,color,pointlist,width=0)
polygon()方法和rect()方法相似,除了第三參數不一樣,polygon()方法的第三個參數接受的是多邊形各個頂點座標組成的列表。ip
例如繪製一個多邊形的魚ci
points = [(200, 75), (300, 25), (400, 75), (450, 25), (450, 125), (400, 75), (300, 125)] pygame.draw.polygon(screen, GREEN, points, 0)
circle(Surface,color,pos,radius,width=0)
其中第1、2、五個參數根前面的兩個方法是同樣的,第三參數指定圓形位置,第四個參數指定半徑的大小。數學
例如繪製一個同心圓:it
pygame.draw.circle(screen, RED, position, 25, 1) pygame.draw.circle(screen, GREEN, position, 75, 1) pygame.draw.circle(screen, BLUE, position, 125, 1)
ellipse(Surface,color,Rect,width=0)
橢圓利用第三個參數指定的矩形來繪製,其實就是將所需的橢圓限定在設定好的矩形中。
pygame.draw.ellipse(screen, BLACK, (100, 100, 440, 100), 1) pygame.draw.ellipse(screen, BLACK, (220, 50, 200, 200), 1)
arc(Surface,color,Rect,start_angle,stop_angle,width=1)
這裏Rect也是用來限制弧線的矩形,而start_angle和stop_angle用於設置弧線的起始角度和結束角度,單位是弧度,同時這裏須要數學上的pi。
pygame.draw.arc(screen, BLACK, (100, 100, 440, 100), 0, math.pi, 1) pygame.draw.arc(screen, BLACK, (220, 50, 200, 200), math.pi, math.pi * 2, 1)
line(Surface,color,start_pos,end_pos,width=1) lines(Surface,color,closed,pointlist,width=1)
line()用於繪製一條線段,而lines()用於繪製多條線段。
其中lines()的closed參數是設置是否首尾相接。
這裏在介紹繪製抗鋸齒線段的方法,aaline()和aalines()其中aa就是antialiased,抗鋸齒的意思。
aaline(Surface,color,startpos,endpos,blend=1) aalines(Surface,color,closed,pointlist,blend=1)
最後一個參數blend指定是否經過繪製混合背景的陰影來實現抗鋸齒功能。因爲沒有width方法,因此它們只能繪製一個像素的線段。
points = [(200, 75), (300, 25), (400, 75), (450, 25), (450, 125), (400, 75), (300, 125)]
pygame.draw.lines(screen, GREEN, 1, points, 1) pygame.draw.line(screen, BLACK, (100, 200), (540, 250), 1) pygame.draw.aaline(screen, BLACK, (100, 250), (540, 300), 1) pygame.draw.aaline(screen, BLACK, (100, 300), (540, 350), 0)