Game Development Reference
In-Depth Information
The OnSave method loops over all of the dynamic options and saves their unique IDs after saving
the number of dynamic options the state has. The OnLoad method begins by clearing the existing
dynamic options and then reinstates each option from the SerializationManager . Once again this is
done using a dynamic_cast and retrieving a shared_ptr from the Option class instances.
The Chest class and the Enemy classes are the only other classes with added OnSave and OnLoad
methods. These are used to save the m_isOpen and m_alive variables from these classes and are
shown in Listing 24-16.
Listing 24-16. The Chest::OnSave , Chest::OnLoad , Enemy::OnSave , and Enemy::OnLoad Methods
virtual void Chest::OnSave(std::ofstream& file)
{
file << m_isOpen;
}
virtual void Chest::OnLoad(std::ifstream& file)
{
file >> m_isOpen;
}
virtual void Enemy::OnSave(std::ofstream& file)
{
file << m_alive;
}
virtual void Enemy::OnLoad(std::ifstream& file)
{
file >> m_alive;
}
These simple methods round out the last of the class changes to support the saving and loading
of the Text Adventure game. At this point I'd encourage you to get the sample code from the
accompanying web site and take a look at the execution of the program in your debugger to get a
feeling for how the ability to be able to reference objects via a centralized system using unique IDs
can be very useful.
Summary
This chapter has given you an overview of a simple mechanism for implementing the ability to save
and load your games. The ifstream and ofstream classes provide a simple mechanism for writing
and reading file data for your programs. These classes follow the usual conventions for stream types
in C++ and should be easily recognizable from the cin , cout , and stringstream examples you have
already seen throughout this topic.
One of the most important lessons to take away from this chapter is the fact that pointers are not
transferrable from one game session to the next. This is true for trying to implement a loading and
saving system and is also true for implementing a multiplayer game. Pointer addresses cannot be sent
from one computer to another to refer to any given object. Instead objects need to be created with a
consistent and persistent unique ID and registered with a centralized system, which ensures there are
no key clashes and can provide access to objects wherever it might be needed in your code.
 
Search WWH ::




Custom Search