Rect(rectangle)指的是矩形,或者長方形,在 Pygame 中我們使用 Rect() 方法來創(chuàng)建一個指定位置,大小的矩形區(qū)域。函數(shù)的語法格式如下:
rect =pygame.Rect(left,top,width,height)
Rect 表示的區(qū)域必須位于一個 Surface 對象之上,比如游戲的主窗口(screen)。上述方法由四個關(guān)鍵參數(shù)值構(gòu)成,分別是 left、top、width、height,為了方便大家理解這些距離的含義,下面給出了一張示意圖:
注意:在 Pygame 中以游戲主窗口的左上角為坐標原點。
下面看一組簡單的使用示例,如下所示:
import pygame
pygame.init()
screen = pygame.display.set_mode((500,300))
pygame.display.set_caption('W3cschool')
image_surface = pygame.image.load("C:/Users/Administrator/Desktop/w3cschool.png")
rect1 = pygame.Rect(0,0,100,100)
# 在原圖的基礎(chǔ)上創(chuàng)建一個新的子圖(surface對象)
image_child= image_surface.subsurface(rect1)
rect2 = image_child.get_rect()
#輸出的矩形大小為 50*50
print(rect2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
#在屏幕上顯示子圖的區(qū)域
screen.blit(image_child,rect1)
pygame.display.update()
程序的運行結(jié)果如下:
圖1:程序運行結(jié)果
從上述運行結(jié)果可以看出,我們在圖片上截取了一個和 rect1 同樣大小的矩形區(qū)域(50*50)。
Rect(矩形區(qū)域)對象還提供了一些常用方法。如下表所示:
方法 | 說明 |
---|---|
pygame.Rect.copy() | 復(fù)制矩形 |
pygame.Rect.move() | 移動矩形區(qū)域,接受一個列表參數(shù) |
pygame.Rect.move_ip() | 移動矩形(無返回) |
pygame.Rect.inflate() | 增大或縮小矩形大小 |
pygame.Rect.clamp() | 將矩形移到另一個矩形內(nèi) |
pygame.Rect.union() | 返回一個兩個矩形合并后的矩形。 |
pygame.Rect.fit() | 按縱橫比調(diào)整矩形的大小或移動矩形。 |
pygame.Rect.contains() | 測試一個矩形是否在另一個矩形內(nèi) |
pygame.Rect.collidepoint() | 測試點是否在矩形內(nèi) |
pygame.Rect.colliderect() | 測試兩個矩形是否重疊 |
同時 Rect 對象也提供了一些關(guān)于矩形大小的常用的屬性,如下所示:
x,y 表示矩形距離 x、y 軸的距離 top, left, bottom, right #在坐標系內(nèi)描述矩形的大小 topleft, bottomleft, topright, bottomright #返回一個描述矩形大小的元組 midtop, midleft, midbottom, midright #返回一個描述矩形大小的元組 center, centerx, centery #(centerx,centery)表示矩形中央坐標(x,y)的值 size, width, height w,h #用于描述矩形的width、height
下面看一組簡單的示例演示,如下所示:
import pygame
# 對應(yīng)left/top/width/height
rect1 = pygame.Rect(0,0,100,100)
print('x的值是{};y的值是{}'.format(rect1.x,rect1.y))
print('bottom的值是{};right的值是{}'.format(rect1.bottom,rect1.right))
# 設(shè)置居中的距離
print(rect1.center,rect1.centerx,rect1.centery)
# 返回值為 (centerx,top)
print(rect1.midtop)
# 返回值為 (right,centery)的元組
print(rect1.midright)
# 返回值為(left,bottom)
print(rect1.bottomleft)
# 返回矩形區(qū)域大小,元組格式
print(rect1.size)
輸出結(jié)果如下:
x的值是0;y的值是0 bottom的值是100;right的值是100 #設(shè)置中心努力 (50, 50) 50 50 (50, 0) #midright (100, 50) #bottomleft (0, 100) #size (100, 100)
我們還可以通過屬性對來設(shè)置,或者者更改矩形區(qū)域的大小,如下所示:
rect1.left = 30
rect1.center = (70,70)
除了通過 Rect 對象來構(gòu)造一個矩形區(qū)域之外,我們還可以使用rect屬性來構(gòu)建一個矩形區(qū)域。在 Pygame 中有許多函數(shù)都提供了rect屬性,比如有下列函數(shù):
surface.fill((0,0,255),rect=(100,100,100,50))
上述代碼會在 surface 對象的區(qū)域內(nèi)選定一個 rect 區(qū)域,并將該區(qū)域填充為藍色(RGB(0,0,255))。
更多建議: