2011-11-19 37 views
1

我想爲我的遊戲創建一個高分榜。 分板包含在文本文件中來自陣列的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 

我該做什麼,所以程序可以排序文本文件中的所有數據,而不僅僅是分數......?

回答

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; 
    } 
} 

,然後排序只能撥打一次結構,(在同時外)的排序方法是這樣的:

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

你真的需要有高於HighScoreData實例?我認爲不行。所以你存儲你的高分是這樣的:

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

基於布勞的樣品,而無需使用LINQ comparers另一種選擇:

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); 
     }