Search code examples
c#winformssln-file

How to store average score and high score in class?


I don't know how to store a player's average score, high score and average time to complete a game in my user.cs class. Whenever the player finishes a round of my game, the average and high scores and average time have to update every time in their labels.

I've tried using arrays and arraylists but I am still unsure because neither seem to work.

Here is my user.cs class:

public class User
    {
        public string fname { get; set; } = "";
        public string lname { get; set; } = "";
        public string username { get; set; } = "";
        public string password { get; set; } = "";

        public User() { }

        public User (string fname, string lname, string username, string password)
        {
            this.fname = fname;
            this.lname = lname;
            this.username = username;
            this.password = password;
        }
    }

I also need to show the users name, username, high score, average score and timing in labels.

The format should be double/float.


Solution

  • You cannot store average score because of the way averages work. While you can count games played by a user by simply increasing the counter by one every time a game finishes, there is no analytical form to advance the average.

    However, if you stored total number of games and total score, then you would be able to advance all the metrics you need.

    class User
    {
        public int HighScore { get; private set; } = 0;
    
        public double AverageScore => 
            this.GamesPlayed > 0 ? this.TotalScore / (double)this.GamesPlayed : 0;
    
        private int GamesPlayed { get; set; } = 0;
        private int TotalScore { get; set; } = 0;
    
        public void GameOver(int score)
        {
            this.HighScore = Math.Max(this.HighScore, score);
            this.GamesPlayed += 1;
            this.TotalScore += score;
        }
    }