[英]How to store average score and high score in class?
我不知道如何在user.cs類中存儲玩家的平均得分,高分和平均時間來完成游戲。 每當玩家完成我的游戲時,平均和高分以及平均時間都必須在他們的標簽中每次更新。
我已經嘗試過使用數組和數組列表,但是我仍然不確定,因為兩者似乎都不起作用。
這是我的user.cs類:
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;
}
}
我還需要在標簽中顯示用戶名,用戶名,高分,平均分和時間。
格式應為double / float。
由於平均工作方式,您無法存儲平均得分。 雖然您可以通過在每次游戲結束時簡單地將計數器增加一來對用戶玩的游戲進行計數,但是沒有分析形式可以提高平均值。
但是,如果您存儲了游戲總數和總得分,那么您將能夠提高所需的所有指標。
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;
}
}
您可以存儲平均值,然后在游戲結束后重新計算。 這樣,您無需存儲將導致溢出問題(早晚)的值(總得分)。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.