Search code examples
pythonpygamepygame-surface

Pygame : create a subsurface that cannot modify parent image, but can be modified by parent


I'm trying to create a subsurface of another surface but only linked by the parent -> child side.

It should have the property of a subsurface if we want to modify the parent surface : the child should also be modified. However it should have the property of a copy if we want to modify the child surface : the parent should not be modified.

For example :

#1 step : all the "subsurfaces" are created from "myimage"
parent = ('myimage.png')
child = parent.subsurface((32,96,32,32))
prop = parent.subsurface((0,0,32,32))
child.blit(prop_to_blit,(0,0))

#2 step : the parent image is modified
parent.blit('otherimage.png')

At the end of the 1st step the child surface should look like child+prop but the parent should stay intact.

At the end of the 2nd step, the parent being modified, all the subsurfaces should be modified too.

For my program to work, I need to blit another image onto the parent image (thus having a "subsurface" function with these properties). I've tried alternatives to this solution, all needed to directly modify the parent image with variable assignment then reloading the file. But it cannot work because of a cyclic module call

Thanks in advance !


Solution

  • A subsurface shares the pixels with the source surface. Therefore it is not possible, that the surface shares the pixels in one direction but not in the other direction. However you can copy() a Surface whenever you want.
    So you have to make a decision. Either you want to share with pixels or you want to copy the pixels. copy the 2st subsurface and blit the 2nd subsurface on it:

    child = parent.subsurface((32,96,32,32)).copy()
    prop = parent.subsurface((0,0,32,32))
    child.blit(prop_to_blit,(0,0))