我在c#中制作一款游戏,并且它拥有前5名玩家的记分牌。 我让它起作用,至少我以为我做了...... 该脚本在数组中输入玩家姓名及其得分的值,但是存在问题。它只是删除了最后一个,所以如果你得到最好的分数你会变成#1,但旧的#1被删除而#2总是#2,除非有人为那个地方做出结果。我的问题是如何从一个地方移动一个数组(这取决于玩家的结果)并删除它的最后一个字符串?
编辑:不能使用列表,因为即时通讯使用该数组做了很多事情。 像这样:
string topScores = sbName[i].Substring(4);
int topScoreInt = Convert.ToInt32(topScores);
答案 0 :(得分:2)
如果你需要使用一个数组而不是List
(它有一个方便的Insert
方法),你可以从最后一个值向前工作,用它替换每一个数字&#39}前任的价值,直到你想要更新的那个:
int place = 2; // Meaning 3rd place, since arrays are zero-based
// Start at end of array, and replace each value with the one before it
for (int i = array.Length - 1; i > place; i--)
{
array[i] = array[i - 1];
}
// Update the current place with the new score
array[place] = score;
答案 1 :(得分:0)
由于您只有5个项目并且评分通常很少,因此一些基本的LINQ代码会更容易且更具可读性:
class Score { public string Name; public int Result;}
Score[] scores = new Score[5];
var newScore = new Score {Name = "Foof", Result=9001};
scores = scores
.Where(s => s != null) // ignore empty
.Concat(Enumerable.Repeat(newScore,1)) // add new one
.OrderByDescending(s => s.Result) // re-sort
.Concat(Enumerable.Repeat((Score)null,4)) // pad with empty if needed
.Take(5) // take top X
.ToArray(); // back to array
旁注:您最好使用List<T>
或SortedList<K,V>
。