I’m rather new to visual basic and I’m making a text based game for a little project in my spare time. The game will have a scoring system, at the end of the game the user’s score will be stored in a text file. I haven’t written the code to write to the file although im sure appending text isn’t difficult. The problem I’m having is displaying the high scores; I can read them in, I can use Split(“,”), I have even displayed the results in a nice table. The problem I am having is displaying the high scores in order of the actual scores.
This is the code i have to build the score table.(NOTE. Pad() is a function i made to pad spaces to the end of strings, this is so they fit into the table correctly. sytax: Pad(string,length of output))
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(" |___________________|______________________________________________| ")
The following is an example of the text file.
2,Zak
10000,Charlie
9999,Shane
90019,Rebecca
Could somebody please help me find a way to sort the lines by the score, maybe I need to take a completely different approach? Thank you very much!
-Charlie
I’m a C# guy, but here goes:
You’ll need this class to hold the values. I have assumed that the
Scorewill always be an integer – if it is something else then this field and theInt32.Parsecall will need to be adjusted to suit.Depending on how robust this needs to be, you may also want to check that the file opens successfully, the
Int32.Parsecall works (theTryParsemethod would be better in this case) and that theline.Splitcall returns an array with two values. Otherwise, that should do the trick.