C# problem

Joined
Mar 27, 2023
Messages
19
Reaction score
1
1726048288399.png

Output on screen.

1726048308750.png

Output from results.txt file.
I want only print out the high score from the file. Only the best result from each person on the screen. In other words, no duplicates of names with scores.
Hope you can help me.

Score.cs
C#:
namespace GuessTheNumber
{
    class Score : IComparable<Score>
    {
        public string PlayerName { get; set; }
        public int GuessCount { get; set; }

        public int CompareTo(Score other)
        {
            if (other == null) return 1;
            if (this.GuessCount == other.GuessCount)
              {
                 return this.PlayerName.CompareTo(other.PlayerName);
              }

            return this.GuessCount.CompareTo(other.GuessCount);
        }
    }
}

HandleHighScore.cs
C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace GuessTheNumber
{
    class HandleHighScore
    {
        private string filePath = "results.txt";

        public bool SaveOrUpdateHighScore(Score score)
        {
            List<Score> scores = FetchHighScore();

          
            scores.Add(score);


           // scores.Sort();

            return SaveAllScores(scores);
        }

        public bool SaveAllScores(List<Score> scores)
        {
            try
            {
                using (StreamWriter sWriter = new StreamWriter(filePath, false))
                {
                    foreach (var score in scores)
                    {
                        sWriter.WriteLine($"{score.PlayerName}: {score.GuessCount} gissningar");
                    }
                }
                return true;
            }
            catch
            {
                Console.WriteLine("Ett fel inträffade vid sparningen.");
                return false;
            }
        }

        public List<Score> FetchHighScore()
        {
            List<Score> scores = new List<Score>();

            if (File.Exists(filePath))
            {
                using (StreamReader sReader = new StreamReader(filePath))
                {
                    string line;
                    while ((line = sReader.ReadLine()) != null)
                    {
                        string[] data = line.Split(':');
                        if (data.Length == 2 && int.TryParse(data[1].Trim().Split(' ')[0], out int guessCount))
                        {
                            scores.Add(new Score { PlayerName = data[0], GuessCount = guessCount });
                        }
                    }
                }

                scores.Sort();
            }

            return scores;
        }
    }
}

GuessNumberGame.cs
C#:
using System;
using System.Collections.Generic;

namespace GuessTheNumber
{
    class GuessNumberGame
    {
        private bool runGame;
        private HandleHighScore saveScoreList;

        public GuessNumberGame()
        {
            saveScoreList = new HandleHighScore();
        }

        public void PlayGame()
        {
            do
            {
                List<int> guesses = new List<int>();
                Random random = new Random();
                int numberToGuess = random.Next(1, 101);

                Console.WriteLine("Start av nytt spel.");

                while (true)
                {
                    Console.Write("Gissa på ett tal mellan 1 och 100: ");
                    int userGuess;

                    while (!int.TryParse(Console.ReadLine(), out userGuess))
                    {
                        Console.Write("Ogiltigt tecken. ");
                    }

                    guesses.Add(userGuess);

                    if (userGuess == numberToGuess)
                    {
                        Console.WriteLine("Grattis, du gissade rätt nummer.");
                        Console.WriteLine($"Det tog dig {guesses.Count} gissningar.");

                        Console.Write("Ange ditt namn: ");
                        string playerName = Console.ReadLine();

                        Score gameScore = new Score
                        {
                            PlayerName = playerName,
                            GuessCount = guesses.Count
                        };
                        saveScoreList.SaveOrUpdateHighScore(gameScore);

                        List<Score> sortedScores = saveScoreList.FetchHighScore();
                        Console.WriteLine("High Scores:");
                        int test;
            
                        foreach (var score in sortedScores)
                        {
                          
                          {

                            Console.WriteLine($"{score.PlayerName}: {score.GuessCount} gissningar");
                          }
                        }

                        break;
                    }
                    else if (userGuess < numberToGuess)
                    {
                        Console.WriteLine(userGuess + " är för lågt! Försök igen.");
                    }
                    else
                    {
                        Console.WriteLine(userGuess + " är för högt! Prova igen.");
                    }
                }

                Console.Write("Vill du spela igen? (ja/nej): ");
                runGame = WillPlay(Console.ReadLine());

            } while (runGame);

            Console.WriteLine("Thank you for playing!");
        }

        private bool WillPlay(string response)
        {
            return response.Equals("ja", StringComparison.OrdinalIgnoreCase);
        }
    }
}
 
Last edited:
Joined
Jul 4, 2023
Messages
466
Reaction score
57
Have you tried anything like this?
[ working code on-line ]
results.txt
Code:
Erik: 6
Anna: 7
Lars: 6
Johan: 8
Anders: 7
Anna: 10
Sofia: 5
Johan: 9
Anna: 4
Lars: 7
C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] lines = File.ReadAllLines("results.txt");
        Dictionary<string, int> scores = new Dictionary<string, int>();

        foreach (string line in lines)
        {
            // Split the line into name and score
            string[] parts = line.Split(':');
            string name = parts[0].Trim();
            int score = int.Parse(parts[1].Trim());

            // If the name is already in the dictionary, keep the highest score
            if (scores.ContainsKey(name))
            {
                if (score > scores[name])
                {
                    scores[name] = score;
                }
            }
            else
            {
                // Add new name and score
                scores[name] = score;
            }
        }

        // Use the Max method from LINQ to find the maximum key length
        int maxNameLength = scores.Keys.Max(k => k.Length);
      
        // Print out the highest scores for each person
        foreach (var entry in scores)
        {
            Console.WriteLine($"{entry.Key.PadRight(maxNameLength)}:{entry.Value.ToString().PadLeft(3)} gissningar");
        }
    }
}
1726166630028.png



BTW, players sorted by score in descending order
[ working code on-line ]
C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] lines = File.ReadAllLines("results.txt");
        Dictionary<string, int> scores = new Dictionary<string, int>();

        foreach (string line in lines)
        {
            // Split the line into name and score
            string[] parts = line.Split(':');
            string name = parts[0].Trim();
            int score = int.Parse(parts[1].Trim());

            // If the name is already in the dictionary, keep the highest score
            if (scores.ContainsKey(name))
            {
                if (score > scores[name])
                {
                    scores[name] = score;
                }
            }
            else
            {
                // Add new name and score
                scores[name] = score;
            }
        }

        // Use the Max method from LINQ to find the maximum key length
        int maxNameLength = scores.Keys.Max(k => k.Length);
        
        // Sort players by score in descending order
        var sortedScores = scores.OrderByDescending(entry => entry.Value);
        
        // Print out the highest scores for each person
        foreach (var entry in sortedScores)
        {
            Console.WriteLine($"{entry.Key.PadRight(maxNameLength)}:{entry.Value.ToString().PadLeft(3)} gissningar");
        }
    }
}
1726167452303.png
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,930
Messages
2,570,072
Members
46,522
Latest member
Mad-Ram

Latest Threads

Top