[Original] Alex
During a game, you usually need to store the game status. The next time you start the game, reload the game and continue the game.
The implementation process is very simple. First, create a struct to define the game parameters to be saved, and then save them as an XML document through the xmlserializer class.
1 Interface Gamedata
2 {
3 Int Gameid;
4 String Playname;
5 Datetime time;
6 }
XNa games can run on Xbox and PC to ensure compatibility between the two. You need to use storagedevice to save the data to the disk.
First, create a storagedevice. In this process, open the guide and terminate it.ProgramUntil the user closes the guide. The user guide must be registered in the game class constructor.
1 Public Alexgame ()
2 {
3 Graphics = New Graphicsdevicemanager ( This );
4 Content. rootdirectory = " Content " ;
5 Components. Add ( New Gamerservicescomponent ( This ));
6 }
Step 2 capture events in the update method.
Code
1 // Get keyboard status
2 Keyboardstate keystate = Keyboard. getstate ();
3 // Guide not displayed
4 If ( ! Guide. isvisible)
5 {
6 // Keyboard press s
7 If (Keystate. iskeydown (Keys. s ))
8 Guide. beginshowstoragedeviceselector (findstoragedevice, " Saverequest " );
9 // Press L on the keyboard
10 If (Keystate. iskeydown (Keys. L ))
11 Guide. beginshowstoragedeviceselector (findstoragedevice, " Loadrequest " );
12 }
Step 3: Define the findstoragedevice Method
Code
1 Private Void Findstoragedevice (iasyncresult result)
2 {
3 Storagedevice = Guide. endshowstoragedeviceselector (result );
4 If (Storagedevice ! = Null )
5 {
6 If (Result. asyncstate. tostring () = " Saverequest " )
7 {
8 // Save game
9 Savegame (storagedevice );
10 }
11 Else If (Result. asyncstate. tostring () = " Loadrequest " )
12 {
13 // Load game
14 Loadgame (storagedevice );
15 }
16 }
17 }
Step 4: Define the savegame and loadgame methods:
Code
1 Private Void Savegame (storagedevice)
2 {
3 Storagecontainer container = Storagedevice. opencontainer ( "Alexgame " );
4 String Filename = Path. Combine (container. path, " Save0001.sav " );
5 Filestream SaveFile = File. Open (filename, filemode. Create );
6 Xmlserializer = New Xmlserializer ( Typeof (Gamedata ));
7 Xmlserializer. serialize (SaveFile, gamedata );
8 SaveFile. Close ();
9 }
Code
Private Void Loadgame (storagedevice)
{
Storagecontainer container = Storagedevice. opencontainer ( " Alexgame " );
String Filename = Path. Combine (container. path, " Save0001.sav " );
If (File. exists (filename ))
{
Filestream SaveFile = File. Open (filename, filemode. Open );
Xmlserializer = New Xmlserializer ( Typeof (Gamedata ));
Gamedata = (Gamedata) xmlserializer. deserialize (SaveFile );
SaveFile. Close ();
}
}
After running the game, press the s key to create a corresponding game save folder in the "document", such as alexgame.