XNA从数组中排序得分

时间:2011-11-19 11:11:14

标签: c# arrays sorting xna

我想为我的游戏创建一个高分榜。 记分板包含文本文件中的前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;

此代码用于从文本文件中读取数据并已在其中添加排序:             尝试             {

            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

我该怎么做,所以程序可以对文本文件中的所有数据进行排序,而不仅仅是分数......?

2 个答案:

答案 0 :(得分:0)

制作名为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;
    }
}

然后以这种方式将调用排序一次,(在while之外)排序方法:

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

您真的需要拥有超过HighScoreData实例吗?我认为不是..所以你用这种方式存储你的高分:

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

答案 1 :(得分:0)

没有使用基于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);
        }