2012-10-15 39 views
1

我對視覺基礎很陌生,在業餘時間爲一個小項目製作基於文本的遊戲。遊戲將有一個評分系統,在遊戲結束時,用戶的評分將被存儲在一個文本文件中。我沒有寫代碼寫入文件,雖然我確定追加文本並不困難。我遇到的問題是顯示高分;我可以閱讀它們,我可以使用Split(「,」),我甚至在一張不錯的表格中顯示了結果。我遇到的問題是按照實際分數的順序顯示高分。 (注意:Pad()是一個函數,我用它來填充空格到字符串的末尾,這樣它們就可以正確放入表格中了。sytax:Pad(string,length輸出))Visual Basic - 讀取.txt,分割,排序和顯示

Dim FStrm As FileStream 
    Dim StrmR As StreamReader 
    FStrm = New FileStream("HighScores.txt", FileMode.Open) 
    StrmR = New StreamReader(FStrm) 
    Dim highScores As New List(Of String) 

    While StrmR.Peek <> -1 
     highScores.Add(StrmR.ReadLine) 
    End While 

    FStrm.Close() 

    Console.WriteLine("  __________________________________________________________________ ") 
    Console.WriteLine("  |  Score  |  Name         |") 
    Console.WriteLine("  |-------------------|----------------------------------------------|") 
    Dim Scores() As String 
    For Each score As String In highScores 
     Scores = score.Split(",") 
     Console.WriteLine("  | {0} | {1} |", Pad(Scores(0), 15), Pad(Scores(1), 40)) 
    Next 
    Console.WriteLine("  |___________________|______________________________________________| ") 

以下是文本文件的示例。

2,Zak 
10000,Charlie 
9999,Shane 
90019,Rebecca 

有人請幫助我找到一種方法來按分數排序線,也許我需要採取一種完全不同的方法?非常感謝你!

-Charlie

回答

0

我是一個C#的傢伙,但這裏有雲:

Dim scores As List(Of UserScore) 
Dim lines As String() 
'Read in all lines in one hit. 
lines = File.ReadAllLines("HighScores.txt") 
scores = New List(Of UserScore) 

For Each line As String In lines 
    Dim tokens As String() 
    'Split each line on the comma character. 
    tokens = line.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 

    'Create a new UserScore class and assign the properties. 
    Dim userScore As UserScore 
    userScore = New UserScore() 
    userScore.Name = tokens(1) 
    userScore.Score = Int32.Parse(tokens(0)) 

    'Add to the list of UserScore objects. 
    scores.Add(userScore) 
Next 

'Sort them by descending order of score. To sort in the other 
'direction, remove the Descending keyword. 
scores = (From s In scores Order By s.Score Descending).ToList() 

你需要這個類來保存值。我假設Score將始終是一個整數 - 如果它是別的東西,那麼此字段和Int32.Parse調用將需要進行調整以適應。

Class UserScore 
    Property Name As String 
    Property Score As Int32 
End Class 

取決於如何穩健這就需要將,你可能還需要檢查文件成功打開,則Int32.Parse調用作品(該TryParse方法是在這種情況下更好),而line.Split調用返回的有兩個值的數組。否則,這應該做的伎倆。