From 82ed5fb784eaaaaf1a093c91ea91c46135886cf2 Mon Sep 17 00:00:00 2001 From: Slavasil Date: Sun, 23 Mar 2025 23:24:09 +0300 Subject: [PATCH] add Leaderboard class --- App/Data/Leaderboard.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 App/Data/Leaderboard.cs diff --git a/App/Data/Leaderboard.cs b/App/Data/Leaderboard.cs new file mode 100644 index 0000000..0f88223 --- /dev/null +++ b/App/Data/Leaderboard.cs @@ -0,0 +1,33 @@ +namespace Game.Data { + internal class Leaderboard { + public static void WriteScore(string playerName, int score) { + var oldScores = ReadScores(); + for (int i = 0; i < oldScores.Count; ++i) { + if (oldScores[i].Item1 == playerName) { + oldScores.RemoveAt(i); + break; + } + } + oldScores.Add((playerName, score)); + oldScores.Sort((a, b) => a.Item2.CompareTo(b.Item2)); + File.WriteAllLines("leaders.txt", oldScores.Select(score => score.Item1 + "\t" + score.Item2.ToString())); + } + + public static List<(string, int)> ReadScores() { + using StreamReader rd = new StreamReader("leaders.txt"); + List<(string, int)> scores = new List<(string, int)>(); + string? line = null; + while ((line = rd.ReadLine()) != null) { + if (line.Length > 0) { + string[] fields = line.Split('\t'); + if (fields.Length < 2) continue; + int score; + if (!int.TryParse(fields[1], out score)) continue; + scores.Add((fields[0], score)); + } + } + scores.Sort((a, b) => a.Item2.CompareTo(b.Item2)); + return scores; + } + } +}