我对视觉基础比较陌生,而且我在业余时间为一个小项目制作一个基于文本的游戏。游戏将有一个评分系统,在游戏结束时,用户的分数将存储在文本文件中。虽然我确定附加文本并不困难,但我还没有编写代码来写入文件。我遇到的问题是显示高分;我可以阅读它们,我可以使用Split(“,”),我甚至在一个漂亮的表中显示结果。我遇到的问题是按实际分数的顺序显示高分。 这是我必须构建得分表的代码。(注意.Pad()是我用来填充空格到字符串末尾的函数,这是因为它们正确地适合表格.sytax:Pad(字符串,长度为输出))
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 :(得分: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
调用返回一个包含两个值的数组。否则,应该这样做。