How to determine if two Pygame subsurfaces refer to the same area?

I have two pygame surfaces (technically subsurface), and I need to check their equality.

Here is my code:

actor.display(mockSurface, Rect((0, 0, 640, 640)))
assert actor.image == actor.spriteSheet.subsurface(Rect((0, 30, 30, 30)))

And here is the code for actor.display:

def display(self, screen, camera_location):
    self.image = self.spriteSheet.subsurface(Rect((0, 30, 30, 30)))
    screen.blit(self.image, (0, 0))

Now here is the error I get from this statement line:

>           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))

They should be equal (I'm wrong), but the statement doesn’t work with some kind of snake trick.

+3
source share
1 answer

Use Surface.get_offset () and Surface.get_parent () to determine if both subsurfaces point to the same area of ​​their parent surface.

>>> 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

Both s1 and s2 belong to different objects, therefore they are not equal.

+1
source

Source: https://habr.com/ru/post/1782061/


All Articles