我有 2 个 pygame 表面(技术上是次表面),我需要测试它们是否相等。
这是我的代码:
actor.display(mockSurface, Rect((0, 0, 640, 640)))
assert actor.image == actor.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
下面是 actor.display 背后的代码:
def display(self, screen, camera_location):
self.image = self.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
screen.blit(self.image, (0, 0))
现在这是我从断言行得到的错误:
> assert teste.image == teste.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
E assert <Surface(30x30x32 SW)> == <Surface(30x30x32 SW)>
E + where <Surface(30x30x32 SW)> = <actor.Actor instance at 0x2f78ef0>.image
E + and <Surface(30x30x32 SW)> = <Surface(120x90x32 SW)>.subsurface(<rect(0, 30, 30, 30)>)
E + where <Surface(120x90x32 SW)> = <actor.Actor instance at 0x2f78ef0>.spriteSheet
E + and <rect(0, 30, 30, 30)> = Rect((0, 30, 30, 30))
这些应该是相等的(我错了吗),但是由于一些鬼鬼祟祟的蛇把戏,断言失败了。
最佳答案
使用 Surface.get_offset() 和 Surface.get_parent() 确定两个子表面是否指向其父表面的同一区域。
>>> parent = pygame.image.load("token1.png")
>>> parent
<Surface(128x128x32 SW)>
>>> s1 = parent.subsurface(pygame.Rect(0, 0, 2, 2))
>>> s2 = parent.subsurface(pygame.Rect(0, 0, 2, 2))
>>> s1
<Surface(2x2x32 SW)>
>>> s2
<Surface(2x2x32 SW)>
>>> s1 == s2
False
>>> s1.get_parent() == s2.get_parent()
True
>>> s1.get_offset() == s2.get_offset()
True
>>> s1.get_parent() == s2.get_parent() and s1.get_offset() == s2.get_offset()
True
s1 和 s2 都指向不同的对象,因此不相等。
关于python - 如何确定两个 Pygame 子表面是否引用同一区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4529685/