Search code examples
pygame

Copy a pygame.Surface object


I'm programming a game in pygame in which you place soldiers and they fight. After they are done fighting, I want the screen to return to where it was before the battle started. I want to copy a the pygame.sprite.Group object containing the soldiers using copy.deepcopy() like so:

oldRUnits = copy.deepcopy(RedUnits)
oldBUnits = copy.deepcopy(BlueUnits)

However, I found out that pygame.sprite.Groups don't like to be deepcopied. It just raises pygame.error. I tried deepcopying each pygame.sprite.Sprite object in the group individually like so:

oldRUnits = []
oldBUnits = []
for i in RedUnits:
    oldRUnits.append(copy.deepcopy(i))
for i in BlueUnits:
    oldBUnits.append(copy.deepcopy(i))

However, they don't like to be deepcopied either so I'm stuck. I want to know if there is a way to copy this and if there is a better way to achieve my goal. Thanks!


Solution

  • I think I have a solution to my problem. Instead of

    oldRUnits = []
    oldBUnits = []
    for i in RedUnits:
        oldRUnits.append(copy.deepcopy(i))
    for i in BlueUnits:
        oldBUnits.append(copy.deepcopy(i))
    

    I could write

    oldRUnits = []
    oldBUnits = []
    for i in RedUnits:
        oldRUnits.append(type(i)(*i.get_init_args()))
    for i in BlueUnits:
        oldBUnits.append(type(i)(*i.get_init_args()))