Question

I have an abstract class Screen and child classes: GameScreen, SpellScreen, StatsScreen, etc.

The game works in this way: a Renderer class creates a root

    Screen screenRoot = new GameScreen()

which then is free to add screens to itself, which then may add screens to themselves and so it goes. Therefore a tree-like structure is formed, every Screen containing a list of its child-screens.

Now I am wondering if it's possible to perform serialization and deserialization on that - I'd like to recreate all the screens in the same hierarchy.

Is it enough to serialize only the screenRoot object, and then deserialize it (provided I want to preserve the whole screens tree), or do I need to traverse the tree myself somehow?

How would you go about serializing this?

P.S. the game is for Android and uses OpenGL ES 2.0.

Was it helpful?

Solution

A hierarchy of objects is no impediment to using Java Serialization, as the latter can cope with arbitrary object graphs - and yes, serializing an object using Java Serialization will serialize all objects it refers to (unless that reference is marked transient). Assuming that's what you want, serializing the hierarchy is as simple as:

try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filename)))) {
   oos.write(rootScreen);
}

and reading as simple as:

try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filename)))) {
    return (GameScreen) ois.readObject();
}

OTHER TIPS

There are two issues here.

First, screens should be just that--screens. They shouldn't contain the "model" or object data that represents your game state; only the view/rendering of that state. So serializing and deserializing, doesn't really make sense. I would suggest looking at your architecture again to see if this is really what you want to do.

If you decide to do it, or if you have another game-state object root that you can serialize (I usually use the Player since it has all the essential data in it), you can easily do this with Gson:

// Save
RootObject o = ...; // The root of the hierarchy to serialize
Gson gson = new Gson();
String serialized - gson.toJson(o); // JSON object, eg. { "Player": { ... } }

// Load
RootObject deserialized = gson.fromJson(serialized, RootObject.class);

You can read more in their user guide.

Second, on the issue of JSON and Gson: I prefer this over standard serialization, because it's robust in the face of changes. If your class definitions change, you can still deserialize objects (albeit you get null/empty fields) instead of a runtime exception; you don't need to worry about versioning your classes, either.

Edit: questions like this are better suited to the Game Dev SE site.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top