0

I'm currently working on a networked game of pong. Once the game has ended, the player name and score will be sent to the server for storage. The player is able to access these highscores from the main menu.

Once there are 5 scores stored on the server, only scores that are beat the currently stored scores are added to the database.

Highscores are stored in a dictionary(string, int) and are then ordered by value.

I'm struggling to create a method which will take a highscore entry(name, score), and check it against the highscores dictionary. if the score is high enough, the dictionary will be reordered and will include the new value.

Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35
Sam
  • 348
  • 1
  • 10

2 Answers2

1

I would create a dictionary variable and simply add scores as I go. Then, when I need to get the high scores, return an ordered enumerable of type KeyValuePair.

public class HighScore
{
    static Dictionary<string, int> scoreBook = new Dictionary<string, int>()
    {
        { "Sam", 300 },
        { "Frodo", 200 },
        { "Bilbo", 100 },
    };
    public static void Main(string[] args)
    {
        AddScore("Gandolf", 250);

        foreach (var entry in GetTopScores())
        {
            Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
        }
    }

    public static void AddScore(string name, int score)
    {
        scoreBook.Add(name, score);
    }

    public static IOrderedEnumerable<KeyValuePair<string, int>> GetTopScores()
    {
        var sortedScoreBook = from entry in scoreBook orderby entry.Value descending select entry;
        return sortedScoreBook;
    }
}
Mitch Stewart
  • 1,253
  • 10
  • 12
0

Personally I wouldn't use Dictionary<TKey,TValue> here, I think that SortedList of KeyValuePairs with comparator that works on values could be better. But if you insist, here you go:

    private int numberOfHighScoresToKeepTrackOf = 5;
    private Dictionary<string,int> _scoresDictionary = new Dictionary<string, int>();

    public void AddScore(KeyValuePair<string, int> newScore)
    {
        if (_scoresDictionary.Count < numberOfHighScoresToKeepTrackOf)
            _scoresDictionary.Add(newScore.Key, newScore.Value);
        else if (_scoresDictionary.Values.Min() < newScore.Value)
                _scoresDictionary.Add(newScore.Key, newScore.Value);

        var top = _scoresDictionary.OrderByDescending(pair => pair.Value).Take(Math.Min(_scoresDictionary.Count, numberOfHighScoresToKeepTrackOf));
        _scoresDictionary = top.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    }
Pawel Troka
  • 853
  • 2
  • 12
  • 33