pygame.Rect
pygame object for storing rectangular coordinates
Rect(left, top, width, height) -> Rect
Rect((left, top), (width, height)) -> Rect
Rect(object) -> Rect
copy the rectangle
moves the rectangle
moves the rectangle, in place
grow or shrink the rectangle size
grow or shrink the rectangle size, in place
sets the position and size of the rectangle
moves the rectangle inside another
moves the rectangle inside another, in place
crops a rectangle inside another
crops a line inside a rectangle
joins two rectangles into one
joins two rectangles into one, in place
the union of many rectangles
the union of many rectangles, in place
resize and move a rectangle with aspect ratio
correct negative sizes
test if one rectangle is inside another
test if a point is inside a rectangle
test if two rectangles overlap
test if one rectangle in a list intersects
test if all rectangles in a list intersect
test if any object in a list intersects
test if all objects in a list intersect
test if one rectangle in a dictionary intersects
test if all rectangles in a dictionary intersect

PYGAME使用RECT对象存储和操作矩形区域。可以从Left、Top、Width和Height值的组合创建RECT。也可以从已经是RECT或具有名为“RECT”的属性的Python对象创建Rect。

任何需要RECT参数的pyGame函数也可以接受这些值中的任何一个来构造RECT。这使得动态创建Rect作为函数的参数变得更容易。

更改RECT的位置或大小的RECT函数返回带有受影响更改的RECT的新副本。原始RECT不会被修改。有些方法有一个替代的“就地”版本,该版本返回NONE,但会影响原始的RECT。这些“就地”方法用“ip”后缀表示。

RECT对象具有几个虚拟属性,可用于移动和对齐RECT:

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

所有这些属性都可以分配给:

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

对大小、宽度或高度的赋值会更改矩形的尺寸;所有其他赋值都会移动矩形,而不会调整其大小。请注意,有些属性是整数,其他属性是整数对。

如果RECT具有非零的宽度或高度,则它将返回 True 进行非零测试。某些方法返回大小为0的Rect以表示无效的矩形。使用冲突检测方法时,大小为0的RECT不会冲突(例如 collidepoint()colliderect() 等)。

RECT对象的坐标都是整数。可以将尺寸值编程为负值,但对于大多数操作而言,这些值被认为是非法的。

其他矩形之间有几个碰撞测试。可以搜索大多数Python容器以查找与单个RECT的冲突。

矩形覆盖的区域不包括像素的最右边缘和最下边缘。如果一个RECT的下边框是另一个RECT的上边框(即,rect1.Bottom=rect2.top),则两者在屏幕上完全相交,但不重叠,并且 rect1.colliderect(rect2) 返回FALSE。

RECT对象也是可迭代的:

r = Rect(0, 1, 2, 3)
x, y, w, h = r

New in pygame 1.9.2: 可以对RECT类进行子类化。方法,如 copy()move() 将识别这一点并返回子类的实例。但是,子类的 __init__() 方法,并且 __new__() 被假定为不接受任何参数。因此,如果需要复制任何额外的属性,则应覆盖这些方法。

copy()
copy the rectangle
copy() -> Rect

返回与原始矩形具有相同位置和大小的新矩形。

PYGAME 1.9新增功能

move()
moves the rectangle
move(x, y) -> Rect

返回按给定偏移量移动的新矩形。X和y参数可以是任何正负整数值。

move_ip()
moves the rectangle, in place
move_ip(x, y) -> None

Rect.move() 方法,但在适当的位置操作。

inflate()
grow or shrink the rectangle size
inflate(x, y) -> Rect

返回一个大小按给定偏移量更改的新矩形。该矩形仍以其当前中心为中心。负值将缩小矩形。注意,使用整数,如果给定的偏移量太小(<2>-2),中心将关闭。

inflate_ip()
grow or shrink the rectangle size, in place
inflate_ip(x, y) -> None

Rect.inflate() 方法,但在适当的位置操作。

update()
sets the position and size of the rectangle
update(left, top, width, height) -> None
update((left, top), (width, height)) -> None
update(object) -> None

就地设置矩形的位置和大小。请参阅参数 pygame.Rect()pygame object for storing rectangular coordinates 以获取此函数的参数。

New in pygame 2.0.1.

clamp()
moves the rectangle inside another
clamp(Rect) -> Rect

返回一个移动到完全位于参数RECT内的新矩形。如果矩形太大,无法放入其中,则它会在参数rect中居中,但其大小不会更改。

clamp_ip()
moves the rectangle inside another, in place
clamp_ip(Rect) -> None

Rect.clamp() 方法,但在适当的位置操作。

clip()
crops a rectangle inside another
clip(Rect) -> Rect

返回一个被裁剪为完全位于参数RECT内的新矩形。如果两个矩形一开始不重叠,则返回大小为0的矩形。

clipline()
crops a line inside a rectangle
clipline(x1, y1, x2, y2) -> ((cx1, cy1), (cx2, cy2))
clipline(x1, y1, x2, y2) -> ()
clipline((x1, y1), (x2, y2)) -> ((cx1, cy1), (cx2, cy2))
clipline((x1, y1), (x2, y2)) -> ()
clipline((x1, y1, x2, y2)) -> ((cx1, cy1), (cx2, cy2))
clipline((x1, y1, x2, y2)) -> ()
clipline(((x1, y1), (x2, y2))) -> ((cx1, cy1), (cx2, cy2))
clipline(((x1, y1), (x2, y2))) -> ()

返回被裁剪为完全位于矩形内的直线的坐标。如果直线不与矩形重叠,则返回空元组。

要裁剪的线条可以是以下任何一种格式(浮点型可以用来代替整型,但它们将被截断):

  • 四个整型

  • 2个列表/元组/向量2个整型

  • 四个整型的列表/元组

  • 2个整数的列表/元组/向量2的列表/元组

返回

返回一个元组,其中给定线的坐标被裁剪成完全在矩形内,如果给定线不与矩形重叠,则返回一个空元组

返回类型

tuple(tuple(int, int), tuple(int, int)) or ()

引发

TypeError -- 如果没有给出线坐标作为上述线格式之一

备注

该方法可用于矩形和直线之间的碰撞检测。请参见下面的示例代码。

备注

这个 rect.bottomrect.right 对象的属性 pygame.Rectpygame object for storing rectangular coordinates 始终位于其实际边框外一个像素处。

# Example using clipline().
clipped_line = rect.clipline(line)

if clipped_line:
    # If clipped_line is not an empty tuple then the line
    # collides/overlaps with the rect. The returned value contains
    # the endpoints of the clipped line.
    start, end = clipped_line
    x1, y1 = start
    x2, y2 = end
else:
    print("No clipping. The line is fully outside the rect.")

New in pygame 2.0.0.

union()
joins two rectangles into one
union(Rect) -> Rect

返回一个完全覆盖所提供的两个矩形区域的新矩形。新的RECT内部可能有原始RECT没有覆盖的区域。

union_ip()
joins two rectangles into one, in place
union_ip(Rect) -> None

Rect.union() 方法,但在适当的位置操作。

unionall()
the union of many rectangles
unionall(Rect_sequence) -> Rect

返回一个矩形与多个矩形的并集。

unionall_ip()
the union of many rectangles, in place
unionall_ip(Rect_sequence) -> None

Rect.unionall() 方法,但在适当的位置操作。

fit()
resize and move a rectangle with aspect ratio
fit(Rect) -> Rect

返回移动并调整大小以适应另一个矩形的新矩形。原始矩形的纵横比被保留,因此新矩形可能在宽度或高度上小于目标。

normalize()
correct negative sizes
normalize() -> None

如果矩形的大小为负数,这将翻转矩形的宽度或高度。矩形将保持在相同的位置,仅交换边。

contains()
test if one rectangle is inside another
contains(Rect) -> bool

当参数完全位于RECT内时,返回TRUE。

collidepoint()
test if a point is inside a rectangle
collidepoint(x, y) -> bool
collidepoint((x,y)) -> bool

如果给定点在矩形内,则返回TRUE。沿右边缘或下边缘的点不被视为在矩形内。

备注

对于RECT和直线之间的冲突检测, clipline() 方法可以使用。

colliderect()
test if two rectangles overlap
colliderect(Rect) -> bool

如果任一矩形的任何部分重叠(上+下或左+右边缘除外),则返回True。

备注

对于RECT和直线之间的冲突检测, clipline() 方法可以使用。

collidelist()
test if one rectangle in a list intersects
collidelist(list) -> index

测试该矩形是否与一系列矩形中的任何一个发生冲突。返回找到的第一个冲突的索引。如果没有发现冲突,则返回索引-1。

collidelistall()
test if all rectangles in a list intersect
collidelistall(list) -> indices

返回包含与RECT冲突的矩形的所有索引的列表。如果没有找到相交的矩形,则返回空列表。

不仅Rect是有效参数,而且这些都是有效调用:

 1Rect = pygame.Rect
 2r = Rect(0, 0, 10, 10)
 3
 4list_of_rects = [Rect(1, 1, 1, 1), Rect(2, 2, 2, 2)]
 5indices0 = r.collidelistall(list_of_rects)
 6
 7list_of_lists = [[1, 1, 1, 1], [2, 2, 2, 2]]
 8indices1 = r.collidelistall(list_of_lists)
 9
10list_of_tuples = [(1, 1, 1, 1), (2, 2, 2, 2)]
11indices2 = r.collidelistall(list_of_tuples)
12
13list_of_double_tuples = [((1, 1), (1, 1)), ((2, 2), (2, 2))]
14indices3 = r.collidelistall(list_of_double_tuples)
15
16class ObjectWithRectAttribute(object):
17    def __init__(self, r):
18        self.rect = r
19
20list_of_object_with_rect_attribute = [
21    ObjectWithRectAttribute(Rect(1, 1, 1, 1)),
22    ObjectWithRectAttribute(Rect(2, 2, 2, 2)),
23]
24indices4 = r.collidelistall(list_of_object_with_rect_attribute)
25
26class ObjectWithCallableRectAttribute(object):
27    def __init__(self, r):
28        self._rect = r
29
30    def rect(self):
31        return self._rect
32
33list_of_object_with_callable_rect = [
34    ObjectWithCallableRectAttribute(Rect(1, 1, 1, 1)),
35    ObjectWithCallableRectAttribute(Rect(2, 2, 2, 2)),
36]
37indices5 = r.collidelistall(list_of_object_with_callable_rect)
collideobjects()
test if any object in a list intersects
collideobjects(rect_list) -> object
collideobjects(obj_list, key=func) -> object

测试该矩形是否与序列中的任何对象发生碰撞。返回找到的第一个碰撞的对象。如果没有发现冲突,则 None 是返回的

如果给出了key,那么它应该是一个接受列表中的对象作为输入并返回一个类似RECT的对象的方法。 lambda obj: obj.rectangle 。如果一个对象有多个类型为RECT的属性,那么key可以返回其中之一。

 1r = Rect(1, 1, 10, 10)
 2
 3rects = [
 4    Rect(1, 1, 10, 10),
 5    Rect(5, 5, 10, 10),
 6    Rect(15, 15, 1, 1),
 7    Rect(2, 2, 1, 1),
 8]
 9
10result = r.collideobjects(rects)  # -> <rect(1, 1, 10, 10)>
11print(result)
12
13class ObjectWithSomRectAttribute:
14    def __init__(self, name, collision_box, draw_rect):
15        self.name = name
16        self.draw_rect = draw_rect
17        self.collision_box = collision_box
18
19    def __repr__(self):
20        return f'<{self.__class__.__name__}("{self.name}", {list(self.collision_box)}, {list(self.draw_rect)})>'
21
22objects = [
23    ObjectWithSomRectAttribute("A", Rect(15, 15, 1, 1), Rect(150, 150, 50, 50)),
24    ObjectWithSomRectAttribute("B", Rect(1, 1, 10, 10), Rect(300, 300, 50, 50)),
25    ObjectWithSomRectAttribute("C", Rect(5, 5, 10, 10), Rect(200, 500, 50, 50)),
26]
27
28# collision = r.collideobjects(objects) # this does not work because the items in the list are no Rect like object
29collision = r.collideobjects(
30    objects, key=lambda o: o.collision_box
31)  # -> <ObjectWithSomRectAttribute("B", [1, 1, 10, 10], [300, 300, 50, 50])>
32print(collision)
33
34screen_rect = r.collideobjects(objects, key=lambda o: o.draw_rect)  # -> None
35print(screen_rect)

New in pygame 2.1.3.

collideobjectsall()
test if all objects in a list intersect
collideobjectsall(rect_list) -> objects
collideobjectsall(obj_list, key=func) -> objects

返回包含与矩形冲突的矩形的所有对象的列表。如果没有找到相交的对象,则返回一个空列表。

如果给出了key,那么它应该是一个接受列表中的对象作为输入并返回一个类似RECT的对象的方法。 lambda obj: obj.rectangle 。如果一个对象有多个类型为RECT的属性,那么key可以返回其中之一。

 1r = Rect(1, 1, 10, 10)
 2
 3rects = [
 4    Rect(1, 1, 10, 10),
 5    Rect(5, 5, 10, 10),
 6    Rect(15, 15, 1, 1),
 7    Rect(2, 2, 1, 1),
 8]
 9
10result = r.collideobjectsall(
11    rects
12)  # -> [<rect(1, 1, 10, 10)>, <rect(5, 5, 10, 10)>, <rect(2, 2, 1, 1)>]
13print(result)
14
15class ObjectWithSomRectAttribute:
16    def __init__(self, name, collision_box, draw_rect):
17        self.name = name
18        self.draw_rect = draw_rect
19        self.collision_box = collision_box
20
21    def __repr__(self):
22        return f'<{self.__class__.__name__}("{self.name}", {list(self.collision_box)}, {list(self.draw_rect)})>'
23
24objects = [
25    ObjectWithSomRectAttribute("A", Rect(1, 1, 10, 10), Rect(300, 300, 50, 50)),
26    ObjectWithSomRectAttribute("B", Rect(5, 5, 10, 10), Rect(200, 500, 50, 50)),
27    ObjectWithSomRectAttribute("C", Rect(15, 15, 1, 1), Rect(150, 150, 50, 50)),
28]
29
30# collisions = r.collideobjectsall(objects) # this does not work because ObjectWithSomRectAttribute is not a Rect like object
31collisions = r.collideobjectsall(
32    objects, key=lambda o: o.collision_box
33)  # -> [<ObjectWithSomRectAttribute("A", [1, 1, 10, 10], [300, 300, 50, 50])>, <ObjectWithSomRectAttribute("B", [5, 5, 10, 10], [200, 500, 50, 50])>]
34print(collisions)
35
36screen_rects = r.collideobjectsall(objects, key=lambda o: o.draw_rect)  # -> []
37print(screen_rects)

New in pygame 2.1.3.

collidedict()
test if one rectangle in a dictionary intersects
collidedict(dict) -> (key, value)
collidedict(dict) -> None
collidedict(dict, use_values=0) -> (key, value)
collidedict(dict, use_values=0) -> None

返回与调用RECT对象相交的第一个键和值对。如果没有发现冲突, None 返回。如果 use_values 为0(默认),则将在碰撞检测中使用DICT的关键点,否则将使用DICT的值。

备注

RECT对象不能用作字典中的键(它们不可哈希),因此必须将它们转换为元组。例如: rect.collidedict({{tuple(key_rect) : value}})

collidedictall()
test if all rectangles in a dictionary intersect
collidedictall(dict) -> [(key, value), ...]
collidedictall(dict, use_values=0) -> [(key, value), ...]

返回与调用RECT对象相交的所有键和值对的列表。如果没有发现冲突,则返回空列表。如果 use_values 为0(默认),则将在碰撞检测中使用DICT的关键点,否则将使用DICT的值。

备注

RECT对象不能用作字典中的键(它们不可哈希),因此必须将它们转换为元组。例如: rect.collidedictall({{tuple(key_rect) : value}})




Edit on GitHub