1. 程式人生 > >Python之Pygame.rect函式

Python之Pygame.rect函式

1.引數設定

Pygame 通過 Rect 物件儲存和操作矩形區域。一個 Rect 物件可以由 left,top,width,height 幾個值建立。Rect 也可以是由 Pygame 的物件所建立,它們擁有一個屬性叫“rect”。

任何需要一個 Rect 物件作為引數的 Pygame 函式都可以使用以上值構造一個 Rect。這樣使得作為引數傳遞的同時建立 Rect 成為可能。

Rect 物件中的大部分方法在修改矩形的位置、尺寸後會返回一個新的 Rect 拷貝,原始的 Rect 物件不會有任何改變。但有些方法比較特殊,它們會“原地”修改 Rect 物件(也就是說它們會改動原始的 Rect 物件),常用rect函式的引數有以下形式:

    x,y
    top, left, bottom, right
    topleft, bottomleft, topright, bottomright
    midtop, midleft, midbottom, midright
    center, centerx, centery
    size, width, height
    w,h

For example:

Rect(left, top, width, height) -> Rect

Rect((left, top), (width, height)) -> Rect

Rect(object) -> Rect

上邊這些屬性均可以被賦值,例如:

    rect1.right = 10
    rect2.center = (20,30)




2.Rect函式

2.1移動型別


    pygame.Rect.copy()  —  拷貝 Rect 物件
    pygame.Rect.move()  —  移動 Rect 物件
    pygame.Rect.move_ip()  —  原地移動 Rect 物件
    pygame.Rect.inflate()  —  放大和縮小 Rect 物件的尺寸
    pygame.Rect.inflate_ip()  —  原地放大和縮小 Rect 物件的尺寸
    pygame.Rect.clamp()  —  將一個 Rect 物件移動到另一個 Rect 物件的中心

    pygame.Rect.clamp_ip()  —  原地將一個 Rect 物件移動到另一個 Rect 物件的中心

給 size,width,height 屬性賦值將改變矩形的尺寸;給其它屬性賦值將移動矩形。注意:一些屬性是整數,一些是整數對。

2.2邏輯型別

    pygame.Rect.clip()  —  獲取兩個 Rect 物件互相重疊的部分
    pygame.Rect.union()  —  將兩個 Rect 物件合併
    pygame.Rect.union_ip()  —  原地將兩個 Rect 物件合併
    pygame.Rect.unionall()  —  將多個 Rect 物件合併
    pygame.Rect.unionall_ip()  —  原地將多個 Rect 物件合併
    pygame.Rect.fit()  —  按照一定的寬高比調整 Rect 物件

    pygame.Rect.normalize()  —  翻轉 Rect 物件(如果尺寸為負數)

#Rect 物件的座標都是整數,size 的值可以是負數,但在大多數情況下被認為是非法的

2.3 檢測型別

    pygame.Rect.contains()  —  檢測一個 Rect 物件是否完全包含在該 Rect 物件內
    pygame.Rect.collidepoint()  —  檢測一個點是否包含在該 Rect 物件內
    pygame.Rect.colliderect()  —  檢測兩個 Rect 物件是否重疊
    pygame.Rect.collidelist()  —  檢測該 Rect 物件是否與列表中的任何一個矩形有交集
    pygame.Rect.collidelistall()  —  檢測該 Rect 物件與列表中的每個矩形是否有交集
    pygame.Rect.collidedict()  —  檢測該 Rect 物件是否與字典中的任何一個矩形有交集

    pygame.Rect.collidedictall()  —  檢測該 Rect 物件與字典中的每個矩形是否有交集

還有一些方法可以實現矩形間碰撞檢測,大多數 Python 的容器可以用於檢索其中的元素與某個 Rect 物件是否碰撞。

Rect 物件覆蓋的範圍並不包含 right 和 bottom 指定的邊緣位置。





對了方便大家移動和對齊,Rect 物件提供以下這些虛擬屬性:

   




複製程式碼

如果一個 Rect 物件的 width 或 height 非 0,那麼將在非 0 測試中返回 True。一些方法返回尺寸為 0 的 Rect 物件,用於表示一個非法的矩形。



還有一些方法可以實現矩形間碰撞檢測,大多數 Python 的容器可以用於檢索其中的元素與某個 Rect 物件是否碰撞。

Rect 物件覆蓋的範圍並不包含 right 和 bottom 指定的邊緣位置。