不带序列化的 Java 深度复制
我一直在为 Android 编写一个纸牌游戏,我非常困惑如何保存我的游戏状态。为了简要解释我的程序,我有一个 Sprite 类用于显示我的卡片,其中包含位图图像、位置点和边界矩形。我继承这个类来创建一个卡片类,它有两个位图,根据卡片是面朝上还是面朝下进行切换,以及用于存储花色和等级的枚举。这些卡片对象放置在 CardStack 对象中,其中包含附加位置和卡片数组列表。游戏模型由各种牌堆以及在牌堆之间移动牌的规则组成。游戏按原样运行得很好。
现在我想弄清楚如何保存我的游戏状态。我想序列化整个游戏对象并将其保存到文件中。然而,有许多对象(位图、点、矩形、颜色等)是不可序列化的。在 C# 中,我知道您可以使用 MemoryStream 并仅复制整个对象,但我在 Java 中找不到不需要所有内容都可序列化的类似方法。 Java中有类似的东西吗?我有更好的方法来构建我的游戏模型对象吗?任何建议将不胜感激。谢谢!
I have been writing a card game for Android, and I am desperately stuck on how to save my game state. To briefly explain my program, I have a Sprite class for displaying my cards which contains a bitmap image, a point for the position, and a bounding rectangle. I inherit this class to make a card class which has two bitmaps which are switched depending on whether the card is face up or down, and enumerations for storing suit and rank. These card objects are place in CardStack objects which contain and additional position, and an arraylist of cards. The game model consists of various CardStacks, and the rules for move cards between stacks. The game works great as is.
Now I am trying to figure out how to save my game state. I would like to serialize my entire game object and save it to a file. However, there are numerous objects (bitmap, point, rectangle, color, etc) that are not serializable. In C#, I know you can use a MemoryStream and just copy the whole object, but I can't find a similar method in Java that does not require everything to be serializable. Is there anything similar in Java? Any better way I could structure my game model object? Any advice would be greatly appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 gui 抽象为业务对象,并使 gui 对象封装这些业务对象,
这样卡片就不需要知道需要显示什么位图(甚至根本不需要显示),
这些业务对象就是您想要的序列化并且可以从反序列化的对象重建 GUI
abstract the gui into business objects and make the gui objects encapsulate these business objects
this way a card doesn't need to know what bitmap it needs to be displayed (or even that it gets displayed at all)
those business objects are what you want to serialize and the gui can be rebuild from the deserialized objects
您始终可以在 Java 的序列化框架内编写自己的自定义序列化方法。请参阅可序列化。
如果您的对象包含不可序列化的对象,Java 的默认实现将会失败,这是正确的,但您可以在上面的方法中定义如何序列化它们。
另外:在 Android 上,您可能需要使用
Parcelable
,这是 Android 的序列化版本。You can always write your own customized serialization methods within Java's serialization framework. See Serializable.
You are correct that Java's default implementation will fail if your object contains non-serializable objects, but you can define how to serialize them in methods above.
Also: on Android, you may want to use
Parcelable
which is Android's version of serialization.查看协议缓冲区 (protobuf)
Take a look at protocol buffers (protobuf)