Pygame有兩種表示矩形區域的方法(就像有兩種表示顏色的方法)。
第一種是四個整數的元組:
左上角的X坐標。
左上角的Y坐標。
矩形的寬度(以像素為單位)。
然后是矩形的高度(以像素為單位)。
第二種方式是
作為pygame.Rect 對象,我們將簡稱為Rect對象。例如,下面的代碼創建一個Rect對象,其左上角位于(10,20),寬200像素,高300像素:
>>> import pygame
>>> spamRect = pygame.Rect(10, 20, 200, 300)
>>> spamRect == (10, 20, 200, 300)
True
關于這一點的一個方便之處是Rect對象自動計算矩形的其他特征的坐標。例如,如果您需要知道我們存儲在spamRect 變量中的pygame.Rect對象右邊緣的X坐標,您只需訪問Rect對象的right 屬性:
>>> spamRect.right
210
Rect對象的Pygame代碼自動計算,如果左邊緣位于X坐標10并且矩形寬度為200像素,則右邊緣必須位于X坐標210.如果重新分配右邊屬性,則所有其他邊緣屬性會自動重新計算:
>>> spamRect.right = 350
>>> spamRect.left
150
這是pygame.Rect對象提供的所有屬性的列表(在我們的示例中,Rect對象存儲在名為spamRect的變量中的變量):
屬性名稱 | 描述 |
---|---|
myRect.left | The int value of the X-coordinate of the left side of the rectangle.(矩形左側X坐標的int值) |
myRect.right | The int value of the X-coordinate of the right side of the rectangle.(矩形右側X坐標的int值) |
myRect.top | The int value of the Y-coordinate of the top side of the rectangle.(矩形頂邊的Y坐標的int值) |
myRect.bottom | The int value of the Y-coordinate of the bottom side.(底邊的Y坐標的int值) |
myRect.centerx | The int value of the X-coordinate of the center of the rectangle.(矩形中心的X坐標的int值) |
myRect.centery | The int value of the Y-coordinate of the center of the rectangle.(矩形中心的Y坐標的int值) |
myRect.width | The int value of the width of the rectangle.(矩形寬度的int值) |
myRect.height | The int value of the height of the rectangle.(矩形高度的int值) |
myRect.size | A tuple of two ints: (width, height)(兩個整數的元組:(寬度,高度)) |
myRect.topleft | A tuple of two ints: (left, top)(兩個整數的元組:(左,上)) |
myRect.topright | A tuple of two ints: (right, top)(兩個整數的元組:(右,頂部)) |
myRect.bottomleft | A tuple of two ints: (left, bottom)(兩個整數的元組:(左,下)) |
myRect.bottomright | A tuple of two ints: (right, bottom)(兩個整數的元組:(右,底)) |
myRect.midleft | A tuple of two ints: (left, centery)(兩個整數的元組:(左,中心)) |
myRect.midright | A tuple of two ints: (right, centery)(兩個整數的元組:(右,居中)) |
myRect.midtop | A tuple of two ints: (centerx, top)(兩個整數的元組:( centerx,top)) |
myRect.midbottom | A tuple of two ints: (centerx, bottom)(兩個整數的元組:( centerx,bottom)) |