using System.Runtime.Serialization;
using QwirkleClassLibrary.Games;
namespace QwirkleClassLibrary.Persistences
{
///
/// This class takes care of managing persistence with regard to the information of the current game, allowing the last game played to be resumed even when returning to the menu or exiting the application.
///
public class GamePersistenceXml : IGamePersistence
{
///
/// The main purpose of this method is to save the data from the game when the user quits the app, so players can continue it later.
///
///
public void SaveGame(Game game)
{
var serializer = new DataContractSerializer(typeof(Game),
new DataContractSerializerSettings() { PreserveObjectReferences = true });
using (Stream writer = File.Create("Game.xml"))
{
serializer.WriteObject(writer, game);
}
}
///
/// This method is used to retrieve the information needed to resume the last game launched on the application.
///
/// A Game.
public Game LoadGame()
{
var serializer = new DataContractSerializer(typeof(Game));
try
{
using (Stream reader = File.OpenRead("Game.xml"))
{
var newGame = serializer.ReadObject(reader) as Game;
return newGame!;
}
}
catch
{
return new Game();
}
}
}
}