[英]Sorting a leaderboard from highest to lowest
我試圖在richTextBox
中獲得richTextBox
排序的測驗分數。 我在名為scoresClass
的類中保存玩家的姓名,測驗和分數。 在測驗的最后,我將類稱為三個richTextBox
,以顯示其名稱,測驗和分數。 然后,我將它們添加到列表中,並將列表寫入文件中。 排行榜(即richTextBox
)設置為等於文件中的數據。
這是我的代碼:
public frmFinal()
{
InitializeComponent();
}
private void frmFinal_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
List<string> scores = new List<string>();
private void frmFinal_Load(object sender, EventArgs e)
{
//sets the leaderboard equal to the file scoreInfo
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
//sets a textbox equal to the players score
rchBxScore.Text = Convert.ToString(scoresClass.score);
rchBxNameScore.Text = scoresClass.name;
rchBxQuizNameScore.Text = scoresClass.quiz;
}
private void btnClearScores_Click(object sender, EventArgs e)
{
//opens the file scoreInfo
FileStream fileStream = File.Open(".\\scoreInfo.bin", FileMode.Open);
//empties the file
fileStream.SetLength(0);
//closes the file
fileStream.Close();
//sets the leaderbaord equal to the file
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
scores.Clear();
}
//creates a bool variable and sets it equal to false
bool saved = false;
private void btnSaveScore_Click(object sender, EventArgs e)
{
//checks if saved equals false
if (saved == false)
{
//if saved equals false, it opens the file scoreInfo
using (StreamWriter scoreInfo = new StreamWriter(".\\scoreInfo.bin", true))
{
scores.Add(scoresClass.name + "\t" + scoresClass.quiz + "\t" + scoresClass.score);
foreach(string score in scores)
{
scoreInfo.WriteLine(score);
}
}
//clears all the players score details
rchBxNameScore.Clear();
rchBxQuizNameScore.Clear();
rchBxScore.Clear();
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
//sets saved to true
saved = true;
}
}
目前,分數是按輸入時間而不是分數進行的。 我不確定如何實際訂購它們。
這是課程:
public class scoresClass
{
public static int score = 0;
public static string name = "";
public static string quiz = "";
public scoresClass(string userName, int userScore, string userQuiz)
{
name = userName;
score = userScore;
quiz = userQuiz;
}
}
由於您是使用StreamWriter
附加到文件的,所以我將文件作為scoreClass
的集合讀回,而不是盲目地讀取文件並將其轉儲到richTextBox
。 遵循這些原則。
我還必須更改您的類定義。
public class scoresClass
{
public int score = 0;
public string name = "";
public string quiz = "";
public scoresClass(string userName, string userQuiz, int userScore)
{
name = userName;
score = userScore;
quiz = userQuiz;
}
}
private List<scoresClass> importScoresFromFile(string path)
{
var listOfScores = new List<scoresClass>();
var rawScores = File.ReadAllLines(path);
foreach (var score in rawScores)
{
string[] info = score.Split('\t');
listOfScores.Add(new scoresClass(info[0], info[1], Convert.ToInt32(info[2])));
}
return listOfScores.OrderByDescending(r => r.score).ToList();
}
將所有樂譜存儲在內存中后,您便可以進行一些LINQ
工作來對它們進行排序。 然后,您可以遍歷List<scoresClass>
中的每個值,並根據需要導出到richTextBox
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.