Search code examples
c#windows-store-appsstoragewindows-store

Saving highscores on Windows Store app?


I created a Windows Phone app a few months ago and I'm now looking to make it for Windows Store too. I've got everything working except saving the highscore. I've tried reading through the APIs but just can't seem to get it for some reason.

So, can anyone tell me what the following Windows Phone code should look like for a Windows Store app? I expected it would be pretty much the same, considering everything else was. Thanks.

private IsolatedStorageSettings appsettings = IsolatedStorageSettings.ApplicationSettings;

private void SetHighScore()
    {
        if (appsettings.Contains("highscore"))
        {
            int high = Convert.ToInt32(appsettings["highscore"]);

            if (score > high) //if the current score is greater than the high score, make it the new high score
            {
                appsettings.Remove("highscore");
                appsettings.Add("highscore", score);

                GoogleAnalytics.EasyTracker.GetTracker().SendEvent("mainpage", "highscore " + score.ToString(), null, score);
            }

            else //if the current score if less than or equal to the high score, do nothing
            {
                //do nothing
            }
        }

        else
        {
            appsettings.Add("highscore", score); //if there is no high score already set, set it to the current score
        }
    }

    private void GetHighScore()
    {
        if (appsettings.Contains("highscore")) //if there is a highscore display it
        {
            int high = Convert.ToInt32(appsettings["highscore"]);
            txbHighScore.Text = high.ToString();
        }

        else //if there is no highscore display zero
        {
            txbHighScore.Text = "0";
        }
    }

Solution

  • In Windows Store App, You can use LocalSettings or RoamingSettings to save and get data. LocalSettings will save your data in one device, RoamingSettings will sync your data on devices with same account. This is sample code for LocalSettings, RoamingSettings is similar:

    public class LocalSettingsHelper
    {
        public static void Save<T>(string key, T value)
        {
            ApplicationData.Current.LocalSettings.Values[key] = value;
        }
    
        public static T Read<T>(string key)
        {
            if (ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
            {
                return (T)ApplicationData.Current.LocalSettings.Values[key];
            }
            else
            {
                return default(T);
            }
        }
    
        public static bool Remove(string key)
        {
            return ApplicationData.Current.LocalSettings.Values.Remove(key);
        }
    }