2015-04-22 86 views
-3

我在c#中製作遊戲,並且擁有前5名玩家的記分牌。 我做到了這一點,至少我以爲我做到了...... 劇本在陣列中輸入玩家姓名和他的得分值,但是存在問題。它只是刪除最後一個,所以如果你取得最佳成績,你就會成爲第一名,但是除非有人爲那個地方做出了結果,否則舊的#1被刪除,並且#2總是#2。我的問題是如何從一個地方移動數組(取決於玩家的結果)並刪除它的最後一個字符串?c#將數組中的元素移動1 for for循環

編輯:不能使用列表,因爲即時通訊與這個數組做很多東西。 像這樣:

string topScores = sbName[i].Substring(4); 
int topScoreInt = Convert.ToInt32(topScores); 
+9

你可以與我們分享你的插入源代碼,所以我們可以看到你已經嘗試過嗎? – LiamK

+3

你最好使用'List <>'和'Insert'。 – juharr

+0

我想你是基於索引更新你的列表。而是使用Insert方法將記錄插入第一個位置並刪除最後一個。 – XtremeBytes

回答

2

如果你需要使用一個數組,而不是List(其中有一個方便Insert方法),你可以工作從正向的最後一個值的方式,來代替每個與它的前任的值,直到你到了一個要更新:

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; 
+0

由於這是關於高分,你可以使用該值,並以相同的方式向前移動,只要分數高於當前索引處的分數,並且同一時間地點的數字 – Alex

+0

與此代碼出現錯誤:http://imgur.com/hIT4cGD – dvdty

+0

你如何初始化你的數組?如果您可以分享您的代碼,這將非常有幫助。它看起來像你應該創建一些類,而不是解析數組字符串......非常迅速變得凌亂 –

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>