-=-=-=-=-=-=-=-=-=-=-

Object Persistence - Saving a Game's State

-=-=-=-=-=-=-=-=-=-=-

Designing a gaming world

We need to create an object which represents our gaming world - something which encapsulates every location and exit within our game. We'll reuse the code for locations and exits from the previous tutorial, and we can use vector objects to store them within our GamingWorld class.

Download GamingWorld.java

GamingWorld

The first thing you should notice when looking at the source code for GamingWorld is its class declaration. The implements keyword means that GameWorld supports an interface, by the name of Serializable (its full name is java.io.Serializable). This interface allows us to write an instance of GameWorld to disk - we don't need to write code to save every individual member variable of GameWorld.

public class GameWorld implements Serializable

Next, take a look at the member variable declarations for GameWorld. You should notice the transient keyword next to the output member.

// Output stream for gaming system
transient private WidthLimitedOutputStream output;

Members marked transient aren't saved when an object is made persistent. As a general rule, you should use this feature sparingly, and usually only on member variables which will be unique to every instantiation of the object. We might save a single copy of the GamingWorld, but hundreds of users may later retrieve that world. Some may be playing the game as a standalone application, some may be playing it over a TCP network connection, others through an applet (remember we're creating a gaming system, not just a single specific type of game). Every time GameWorld is retrieved, we want a new output stream, so we don't want to retain any details of the original.

The remainder of the code is pretty self-explanatory, and has plenty of comments to explain the details. Most of the code is similar to the LocationDemo class from the previous tutorial, though you'll note that no location or exits are actually created. Instead, an application (a game design tool, or a one-off application) will create an instance of GameWorld, populate it with data, and then save it to disk. In the next section, we'll do just this!

<-- Back to "Creating a text-adventure game"

Prev | Next