Storing unpicklabe pygame.Surface objects in exter

2019-07-02 00:08发布

So I've got a problem - I'm writing a game prototype in Python, using Pygame, and I want to save my games. All of the game-related data is in three instances of certain classes, and I want to save these three instances to a file. However, I've tried pickling these instances, and it doesn't work. Instead, I get "TypeError: can't pickle Surface objects". This is a problem, because I want to store Surface objects.

I'm open to any alternatives to pickling that there may be, using any other kind of data type. The important thing is that these instances get stored, and that their data is then retrievable later on. So what can I do to overcome this issue? Please keep in mind, I'm not a very experienced programmer, having learned Python in my spare time a year ago, and I can't write much of any other language, though I'm slowly learning C++.

2条回答
Anthone
2楼-- · 2019-07-02 00:39

Reading http://docs.python.org/library/pickle.html#pickle-protocol, you need to either have Surface objects export a reduce method or use the copy_reg module to tell pickle how to handle that data as documented in http://docs.python.org/library/copy_reg.html#module-copy_reg.

Either way what pickle needs is a function that will turn a blob it can't handle into (some_class, [arguments here]). And then when you unpickle it will construct a new thing of that class with those arguments.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-02 01:02

The basic point of pickling is that you should be able to serialise the object somehow. An SDL surface is an in memory object holding a lot of run time state. Trying to serialise it is not totally sensible.

What you should do is to decouple the state of your game from the rendering components so that you can serialise just those (pickling or whatever).

It's like trying to save the state of a video by somehow saving the memory buffers holding the decoded video. This will not work. Instead, how you save it is to serialise the location of the video file and the time offset. Then you can continue playback upon load the next time you restore your application.

查看更多
登录 后发表回答