Python Pygame Rect center可以';t覆盖Rect';s左
在下面的代码中,我向self.rect添加一个中心,在它前面添加一个top和left属性(这只用于学习和理解pygame行为)。当我添加“顶部”属性时,顶部似乎会被中心覆盖,但在中心出现之前使用“左”会更改块的x位置。有人能解释为什么左边没有被中心覆盖吗Python Pygame Rect center可以';t覆盖Rect';s左,python,pygame,rect,Python,Pygame,Rect,在下面的代码中,我向self.rect添加一个中心,在它前面添加一个top和left属性(这只用于学习和理解pygame行为)。当我添加“顶部”属性时,顶部似乎会被中心覆盖,但在中心出现之前使用“左”会更改块的x位置。有人能解释为什么左边没有被中心覆盖吗 import pygame pygame.init() screen=pygame.display.set_mode((500,500)) class Block(pygame.sprite.Sprite): def __ini
import pygame
pygame.init()
screen=pygame.display.set_mode((500,500))
class Block(pygame.sprite.Sprite):
def __init__(self):
super(Block, self).__init__()
self.image=pygame.Surface((50,50))
self.image.fill((0,0,200))
self.rect=self.image.get_rect(top=400,center=(0,0))
#this will obviously be overwritten by center, but not the following, why?
#self.rect=self.image.get_rect(left=400,center=(0,0))
b=Block()
blockGrp=pygame.sprite.Group()
blockGrp.add(b)
print blockGrp
while 1:
pygame.time.wait(50)
for e in pygame.event.get():
if e.type==pygame.QUIT:
pygame.quit()
blockGrp.draw(screen)
pygame.display.flip()
调用
get_rect
函数时使用的关键字最终作为dict
传递给函数
然后,Rect
类*迭代该dict
并调用相应的setter函数
现在请注意,dict
中项目的顺序与创建该dict
时使用的顺序不同
例如,尝试在python解释器中运行以下代码:
>>> {"top": 400, "center": (0, 0)}
{'top': 400, 'center': (0, 0)}
>>> {"left": 400, "center": (0, 0)}
{'center': (0, 0), 'left': 400}
>>>
正如您所看到的,当您使用…get_rect(left=400,center=(0,0))
时,会创建一个dict
,如{'center':(0,0),'left':400}
(这是一个实现细节,可能会根据您使用的python解释器而改变)
因此,首先将设置center
,然后将设置left
现在,如果您使用…get_rect(top=400,center=(0,0))
,将生成类似{'top':400,'center':(0,0)}
的命令,并且将首先设置top
,然后设置center
有关dict
如何在内部工作的更多信息,请参阅精彩答案
这就是说,如果您想设置相互冲突的多个属性(例如top
和center
),您应该手动调用setter,例如
self.rect = self.image.get_rect(center=(0,0))
self.rect.top = 400
*它不是一个真正的Rect
类,因为它是用C实现的,所以它最终是一个C函数来完成工作