Saving High Score with Serialized Dictionary Example

using System.IO; using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [Serializable] //Make sure to add this statement to make the class Serializable class ScoreData { public Dictionary<int, int> highScores = new Dictionary<int, int>(); public bool AddScore(int level, int score) /*Add the score to the dictionary, under these conditions: - If the dictionary also has a key for the given level, only add the score if it's greater than the currently stored score. - If the dictionary does not contain a key for the level, add the score as a new key-value pair, but only if the score is greater than 0 Word of caution: Calling the Add() function on a key that is already in the dictionary will result in an error, so that's why we check to see if the dictionary contains the key with the ContainsKey function first. */ { if(highScores.ContainsKey(level) && score > 0) { if(score > highScores[level]) { //If there is already a score stored for this level, rather than using Add(), we can just change the stored value with this bracket notation. highScores[level] = score; return true; } } else { if(score > 0) { highScores.Add(level, score); return true; } } return false; } public int GetScore(int level) /* If the dictionary has a key-value pair for the level, we retrieve and return the score. Otherwise return -1. You can decide how to handle a -1 return value based on your needs. */ { if(highScores.ContainsKey(level)) { return highScores[level]; } else { return -1; } } public bool SaveData() /* Write the high score data out in binary form to a file.*/ { IFormatter formatter = new BinaryFormatter(); //This object will be uses to convert the data to binary format try { Stream stream = new FileStream("SaveData.txt", FileMode.Create, FileAccess.Write); formatter.Serialize(stream, this); //Our formatter object will now write the data to file stream.Close(); Console.WriteLine("Data saved"); return true; } catch(Exception e) { Console.WriteLine("Data not saved"); Console.WriteLine(e.StackTrace); } return false; } public bool LoadData() { IFormatter formatter = new BinaryFormatter(); //This object will be uses to convert the data back from binary format try { Stream stream = new FileStream("SaveData.txt", FileMode.Open, FileAccess.Read); ScoreData objnew = (ScoreData)formatter.Deserialize(stream); //Our formatter object will read the data from the file and convert it to an object. Don't forget the cast to ScoreData! highScores = objnew.highScores; stream.Close(); } catch(Exception e) { Console.WriteLine("Saved data not loaded"); return false; } return true; } } class Program { static void Main() { ScoreData data = new ScoreData(); data.AddScore(1, 20); data.AddScore(2, 35); data.AddScore(2, 50); Console.WriteLine("Level 1 Score: " + data.GetScore(1)); Console.WriteLine("Level 2 Score: " + data.GetScore(2)); Console.WriteLine("Level 3 Score: " + data.GetScore(3)); data.SaveData(); data.LoadData(); Console.WriteLine("After loading the saved data:"); Console.WriteLine("Level 1 Score: " + data.GetScore(1)); Console.WriteLine("Level 2 Score: " + data.GetScore(2)); Console.WriteLine("Level 3 Score: " + data.GetScore(3)); } }
A demonstration of how to save data to a file and read it from a file by using serialization in C#.

To learn more about the game BrainBouncer (currently being converted to MonoGame), check the devlog at https://cloudyheavengames.itch.io/brain-bouncer/devlog/.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.