python - 如何确定两个 Pygame 子表面是否引用同一区域?

标签 python pygame

我有 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/

相关文章:

python - Django:远程访问 PythonAnywhere MySQL 数据库

python - 如何根据已经制作的 pandas 日期范围系列对特定日期进行分类(排序)?

python - Pygame - 我的 Sprite 'drifts' 穿过田野

python - 将 nltk 绘制的解析树保存到图像文件

python - TFLearn CovNet 示例导致使用 CIFAR-10 时出现错误

python - 为什么我的碰撞测试总是返回 'true',为什么图像矩形的位置总是错误的 (0, 0)?

python - Pygame.key.get_pressed() 中的关键常量值是什么?

python - 为什么这个寻路功能会崩溃?

python - 如何用pymunk实现n体模拟?

python - 音频处理