来自数组的XNA排序分数

本文关键字:排序 XNA 数组 | 更新日期: 2023-09-27 18:15:06

我想为我的游戏创建一个高分板。分数板包含文本文件

中的前5名分数

文本文件是这样的:

alpha, 3500
beta, 3600
gamma, 2200
delta, 3400
epsilon, 2000

,这是我的代码:

    [Serializable]
    public struct HighScoreData
    {
        public string[] PlayerName;
        public int[] Score; 
        public int Count;
        public HighScoreData(int count)
        {
            PlayerName = new string[count];
            Score = new int[count];
            Count = count;
        }
    }
    static HighScoreData highScores;

this代码用于从文本文件中读取数据,并且已经在其中添加了排序:试一试{

            using (StreamReader sr = new StreamReader("highscore.txt"))
            {
                string line;
                int i = 0;
                //file = new StreamReader(filePath);
                while ((line = sr.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');                       
                    highScores.PlayerName[i] = parts[0].Trim();
                    highScores.Score[i] = Int32.Parse(parts[1].Trim());                       
                    i++;
                    Array.Sort(highScores.Score);
                }

            }

        }

我是这样画的:

        for (int i = 0; i < 5; i++)
        {
            spriteBatch.DrawString(spriteFont, i + 1 + ". " + highScores.PlayerName[i].ToString()
           , new Vector2(200, 150 + 50 * (i)), Color.Red);
            spriteBatch.DrawString(spriteFont, highScores.Score[i].ToString(),
                new Vector2(550, 150 + 50 * (i)), Color.Red);
        }

的问题是,当我运行游戏,它只排序得分,而不是球员的名字。并且,文本文件中的第一和第二分数被标识为"0"。它显示如下:

   alpha 0
   beta 0
   gamma 2000
   delta 2200
   epsilon 3400

我必须做什么,使程序可以排序文本文件中的所有数据,而不仅仅是分数…?

来自数组的XNA排序分数

基于Blau的示例使用LINQ的另一个不使用比较器的选项:

struct PlayerScore
{
    public string Player;
    public int Score;
    public int DataYouWant;
}

然后是填充列表并对其排序的示例:

        List<PlayerScore> scores = new List<PlayerScore>();
        Random rand = new Random();
        for (int i = 0; i < 10; i++)
        {
            scores.Add(new PlayerScore()
            {
                Player = "Player" + i,
                Score = rand.Next(1,1000)
            });
        }
        scores = (from s in scores orderby s.Score descending select s).ToList();
        foreach (var score in scores)
        {
            Debug.WriteLine("Player: {0}, Score: {1}", score.Player, score.Score);
        }

创建一个名为PlayerScore的结构体

struct PlayerScore 
{
    public string Player;
    public int Score;
    public int DataYouWant;
    public static int Compare(PlayerScore A, PlayerScore B)
    {
        return A.Score - B.Score;
    }
}

,然后只调用一次Sort方法,(在while语句之外),如下所示:

Array.Sort<PlayerScore>( yourArray, PlayerScore.Compare );

你真的需要有更多的HighScoreData实例吗?我认为不……所以你可以这样存储你的高分:

static PlayerScore[] highScores = new PlayerScore[MaxHighScorePlayers];