将Highscorelist从文本文件中读取到按分数

时间:2018-04-10 19:46:58

标签: c# winforms list text-files

我编写了一个游戏。在游戏中,玩家收集了积分,下一步玩家可以在文本框中写下他的名字,然后点击"发送"按钮,他的名字和他的积分将被保存在.txt文件中
玩家可以在textBox中读取他或其他玩家姓名的高分,其中会读出保存的文本文件的名称和分数。 文本文件如下所示:

[Name]     [Points]
 Name1      60
 Name2      20
 Name3      90
 Name4      80

正如您所看到的,我的问题是,文本文件没有按分数排序。如何编写TextBox或具有最高编号的播放器是第一个,第二个等的文本文件?

当前代码:

using System.IO;
private void button1_Click(object sender, EventArgs e)
{
        s_Textfile = "Highscore.txt";
        StreamWriter o_StreamW;
        if (!File.Exists(s_Textfile))
        {
            o_StreamW = File.CreateText(s_Textfile);
            o_StreamW.Close();
        }
        string s_Spacebar = "";
        s_Name = PlayersName.Text; //The Name the player wrotes in the textBox
        s_Highscore = Points.Text; //The Points the Player has

        o_StreamW.WriteLine(s_Name + s_Spacebar+ s_Highscore);
        o_StreamW.Close();
 }

这就是我的Highscore TextBox目前的样子:

StreamReader o_StreamR;
string s_Line = "";
string s_AllLines = "";

o_StreamR = new StreamReader(GameOverScreen.s_Textfile);
while (o_StreamR.Peek() != -1)
{
    s_Line= o_StreamR.ReadLine();
    s_AllLines = s_AllLines + s_Line + "\r\n";
}
o_StreamR.Close();
HighscoreRichTextBox.Text += "Name:             Score:" + "\r\n";
HighscoreRichTextBox.Text += s_AllLines;

1 个答案:

答案 0 :(得分:0)

我首先会使用标签作为播放器名称和分数的分隔符,因为它更容易解析。创建一个包含分数和名称的结构,然后读入文件内容,创建列表,排序和输出。

    //struct to hold the values
    struct highScoreEntry
    {
        public string PlayerName;
        public string Score;
        public highScoreEntry(string playerName, string playerScore)
        {
            PlayerName = playerName;
            Score = playerScore;
        }
    }



    List<highScoreEntry> allScores = new List<highScoreEntry>();
    using (System.IO.StreamReader sr = new StreamReader(@"Path to file"))
    {
        //skip the first line name and score titles
        string line = sr.ReadLine();
        while (!sr.EndOfStream)
        {
            line = sr.ReadLine();
            string[] lineParts = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
            allScores.Add(new highScoreEntry(lineParts[0], lineParts[1]));
        }

    }
    'sort in descending order using OrderByDescending
    List<highScoreEntry> sortedList = allScores.OrderByDescending(i => i.Score).ToList<highScoreEntry>();
    string highScoreText = "Player\tScore\r\n";
    foreach (highScoreEntry item in sortedList)
    {
        ''can be written directly into the textbox but for the example write it to a string
        highScoreText += item.PlayerName + "\t" + item.Score + "\r\n";
    }
    //add it to the textbox
    HighscoreRichTextBox.Text = highScoreText;

    }