2012-11-29 57 views
1

很基本,但我正在創建一款遊戲,我將在遊戲中擁有2到4名玩家,我需要知道如何向用戶詢問將有多少玩家將這些數量存儲在我的陣列中供以後使用?如何將玩家存儲在數組中?

這是我寫到目前爲止

{ 
     int NumberofPlayers; 
     { 
      do 
      { 
       Console.WriteLine("Please enter number of players (2-4): "); 
       String StringNumberOfPlayers = Console.ReadLine(); 
       NumberofPlayers = int.Parse(StringNumberOfPlayers); 

      } 
      while (NumberofPlayers > 4 || NumberofPlayers < 2); 
     } 


     // need get the number of players and set the required elements in 
     // playerPositions to 0 on the board 
    } 
      static int [] PlayerPositions = new int [4]; 

    static void Main() 
    { 
     ResetGame(); 
    } 
} 

}

+1

我看到你得到了玩家的數量,那麼是什麼阻止你重置PlayerPositions數組中的值?請發佈您面臨的具體問題,而不是要求海報爲您編寫代碼。 – ryadavilli

回答

3

你是在正確的軌道上,只是用NumberofPlayers

static int [] PlayerPositions; 

public void ResetGame() 
{ 
    int NumberofPlayers; 
    do 
    { 
     Console.WriteLine("Please enter number of players (2-4): "); 
     String StringNumberOfPlayers = Console.ReadLine(); 
     NumberofPlayers = int.Parse(StringNumberOfPlayers); 
    } 
    while (NumberofPlayers > 4 || NumberofPlayers < 2); 

    // need get the number of players and set the required elements in 
    // playerPositions to 0 on the board 
    PlayerPositions = new int [NumberofPlayers]; 
} 
0

對於這種大小分配陣列,何不你剛剛創建了一個PlayerPositions列表。

List<PlayerPositions> players = new List<PlayerPositions>(); 

根據來自用戶的輸入,一顆顆對象添加到上面的列表中。

while (NumberOfPlayers > 0) 
{ 
players.Add(new PlayerPositions()); 
NumberOfPlayers--; 
} 
+0

最多隻能使用4個使用靜態數組的玩家可能是最好的解決方案(取決於對象的複雜性)。至於你的循環,我會使用第二個變量,否則你會失去玩家的數量(除非你使用列表長度)。 – Mario

+0

這只是一個例子。當然,你想存儲來自用戶的輸入。 – Tushar

1

將數組大小設置爲NumberofPlayers。

PlayerPositions = new int [NumberofPlayers];