/// <summary> /// Wrties a <see cref="SavedGame"/> object to a specific file. /// </summary> /// <param name="savedGame">An object storing the information about the saved game.</param> /// <param name="fileName">The name of the file which the saved game should be written to. /// </param> private static void SaveToFile(SavedGame savedGame, string fileName) { // Get raw saved game XML document XDocument savedGameXml; using (var stream = new MemoryStream()) { var xmlSerializer = new XmlSerializer(typeof(SavedGame)); xmlSerializer.Serialize(stream, savedGame); stream.Position = 0; savedGameXml = XDocument.Load(stream); } // Compute hash on the raw saved game XML document and append it to the document string base64Hash = GetSavedGameHash(savedGameXml); var hashElement = new XElement(HashElementName, base64Hash); savedGameXml.Root.Add(hashElement); // Compress the saved game XML document and write it to the specified file using (FileStream fileStream = File.Create(fileName)) using (var compressionStream = new DeflateStream(fileStream, CompressionMode.Compress)) { savedGameXml.Save(compressionStream, SaveOptions.DisableFormatting); } }
/// <summary> /// Saves a game to a file chosen by the user. /// </summary> /// <param name="game">The game to be saved.</param> /// <returns><see langword="true"/> if the user has chosen to save the game and the saved /// game file has been created successfully.</returns> public static bool SaveGame(Game game) { string fileName; if (!PromptForFileToSave(out fileName)) return false; // Create saved vertex objects var savedVertices = new Dictionary<ViewModels.Vertex, Vertex>(); int idCounter = 0; foreach (ViewModels.Vertex vertex in game.Level.GameObjects.OfType<ViewModels.Vertex>()) { var savedVertex = new Vertex { Id = idCounter++, X = vertex.X, Y = vertex.Y, }; savedVertices[vertex] = savedVertex; } // Attach connected vertex IDs to saved vertex objects foreach (KeyValuePair<ViewModels.Vertex, Vertex> pair in savedVertices) { pair.Value.ConnectedVertexIds = pair.Key.ConnectedVertices .Select(d => savedVertices[d].Id) .ToArray(); } // Create saved game objects var savedGame = new SavedGame { Version = CurrentVersion, CreationDate = DateTime.Now, LevelNumber = game.LevelNumber, VertexCount = game.Level.VertexCount, IntersectionCount = game.Level.IntersectionCount, Vertices = savedVertices.Values.ToArray(), }; // Save the saved game object to the specified file SaveToFile(savedGame, fileName); return true; }