using System.IO;
using System;
using System.Collections.Generic;
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;
}
}
}
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));
}
}
A demonstration of how to score high scores in a dictionary (key-value pair data structure) 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/.
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.