1

I have an issue regarding copy.deepcopy and pygame surface objects.

Regularly, I use WSL and python to execute python (because I have to run windows on my machine but I hate the commandline interface of windows). I'm learning pygame - making a simple game. Everything is working fine, but I tried to launch it with my regularly installed python3 and pygame in AppData, which normally works, but this time it returns an error which doesn't happen in the WSL.

The error is: TypeError: can't pickle pygame.Surface objects Here's the code regarding the error.

player = Player(start)
temp = deepcopy(player)

and here's the class itself:

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join('img','player.png'))
        self.r = 17
        self.rect = self.image.get_rect()
        self.rect.center = (pos[0] + 8.5, pos[1] + 8.5)
        self.rect.inflate_ip(-2,-2)
        self.vel = Vector(0,0)

Now why am I doing what I'm doing. I'm making stuff from scratch, I didn't look up a similar game or anything, I just went. The point is, on the game field, there's a player and there's walls. The player can not move through walls.

The way I do that is - before moving, I make a deepcopy of the player and the copy makes the move instead. Then I check for wall collision and if the copy didn't hit a wall, I move the original player. Then I delete the copy. This is a very sloppy way, but I wasn't able to come up with a better idea.

I want to make this work. I don't mind if anyone advises me a better way to copy the player or just implement the movement in a different way. Should anyone want to see more of the code, tell me and I'll happily give you more snippets :)

Thanks for any help in advance. P.S. This is not a homework, it actually is procrastinating from homework lol

Welsy
  • 77
  • 11
  • Take a look at [this answer](https://stackoverflow.com/a/45017561/6220679). – skrx Jan 26 '18 at 17:21
  • Also, please don't post or link your whole project here and instead provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve). Then we can try to reproduce the error and figure out how to solve the problem. – skrx Jan 26 '18 at 17:26
  • Ayy, my bad, edited :) I will look into the answer, thanks for responding. – Welsy Jan 26 '18 at 18:00

1 Answers1

1

There's no reason to copy the entire player object.

If you just use the Rect of your sprites to check for collisions, you only need to move that very Rect with the move function. It will return a new, updated Rect which you can then use to check for collisions.

If there's a collision, do nothing. If there's no collision, allow the move by changing the original Rect, e.g. with move_ip.

sloth
  • 99,095
  • 21
  • 171
  • 219