简体   繁体   中英

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.

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;
    }
}

You can store the average and then recalculate after a game finishes. This way you don't need to store a value (totalscore) that will cause overflow issues (sooner or later).

class User
{
    public int HighScore { get; private set; } = 0;

    public double AverageScore { get; private set; } = 0;

    private int GamesPlayed { get; set; } = 0;

    public void GameOver(int score)
    {
        this.HighScore = Math.Max(this.HighScore, score);
        // get the prev total score then increase with the current score and get the new average in the end (also increase the GamesPlayed)
        this.AverageScore = ((this.AverageScore * this.GamesPlayed) + score) / ++this.GamesPlayed;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM