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

Object Persistence - Saving a Game's State

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


Creating a gaming world

Each game will have a unique gaming world. A gaming world is created by the game designer - ideally using a GUI tool that makes it easy to link locations and exits together. For the moment, however, we'll use a simple application that creates a very small gaming world, and links the various locations and exits to each other.

Our application will create a new file, and through this write an instance of a GameWorld object to disk. Creating a new file is extremely simple, using the FileOutputStream class. We must enclose our code inside a try { ... } catch block, as I/O can raise run-time exceptions. The FileOutputStream constructor takes the name of a file, and provides us with the ability to write data to disk.

try
{
	// Create a file to write game system
	FileOutputStream out = new FileOutputStream (filename);

	// Code to write instance of GamingWorld will go here
}
catch (Exception e)
{
	System.err.println ("Unable to create game data");
}

Using this file stream, we will then create an ObjectOutputStream. The ObjectOutputStream class allows us to write instances of objects in a persistent manner, and takes as a constructor another inputstream. Putting the two together, we can write an object (in this case, our GamingWorld) to disk. Once the streams are created, it takes only a single line of code to write out our entire data structure! Easy indeed.

// Create an object output stream, linked to out
ObjectOutputStream objectOut = new ObjectOutputStream (out);

// Write game system to object store
objectOut.writeObject (game);

// Close object output stream
objectOut.close();

Source

The full source code for the CreateGamingWorld is available, and extremely easy to use. You can execute CreateGamingWorld, or just download the data file it builds. If you've dealt with persistence under Java before, feel free to skip the source code and download the data (new users are advised to at least examine the code before proceeding).

Download CreateGameWorld.java
Download GameWorld data

In the next section, we'll write a small game that uses an ObjectInputStream to load the GameWorld data, and allows users to walk around inside the world we've created.

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

Prev | Next