部分pygame.rect源代码如下
class Rect(object):
x: int
y: int
top: int
left: int
bottom: int
right: int
topleft: Tuple[int, int]
bottomleft: Tuple[int, int]
topright: Tuple[int, int]
bottomright: Tuple[int, int]
midtop: Tuple[int, int]
midleft: Tuple[int, int]
midbottom: Tuple[int, int]
midright: Tuple[int, int]
center: Tuple[int, int]
centerx: int
centery: int
size: Tuple[int, int]
width: int
height: int
w: int
h: int
__hash__: None # type: ignore
示意图
- 除 x,y wight,height以外, 实际英文单词含义为 top, left bottom ,right 四条边的坐标(取不为0的坐标)
- x,y : 矩形左上A点坐标, 与left ,top 相同
- bottom,right : 右下B点坐标
- 其余属性均为交点,或中点的x,y坐标组成的元组,望图思意即可
- 增大图形时考虑 wight,height(h,w属性与其相同)
测试代码
import pygame
def test():
""" 测试pygame.rect中Rect类的属性 """
# 初始化pygame,设置background
pygame.init()
screen = pygame.display.set_mode([1200, 600])
pygame.display.set_caption("backgroundd")
pygame.display.update()
# 获取分辨率,可以不加
pygame.display.list_modes()
# 获取 surface 的外接矩形
screen_rect = screen.get_rect()
# 创建 Rect 实例 Rect(left, top, width, height)
rect = pygame.Rect(20, 20, 100, 300)
rect_color = [250, 250, 250]
# rect.x = 0
# rect.y = 0
# rect.bottom = 600
# rect.right = 1200
rect.h = 600
while True:
# background 填充颜色
screen.fill([0, 0, 0])
# 画出外接矩形
pygame.draw.rect(screen, rect_color, rect)
# 更新整个 surface 对象
pygame.display.flip()
test()
参考: