【问题标题】:How to store the players in an array?如何将玩家存储在数组中?
【发布时间】:2012-11-29 12:04:38
【问题描述】:

非常基本,但我正在创建一个游戏,我将在游戏中有 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();
    }
}

}

【问题讨论】:

  • 我看到你得到了玩家的数量,那么是什么阻止你重置 PlayerPositions 数组中的值?请发布您面临的具体问题,而不是要求发帖者为您编写代码。

标签: c# arrays storage


【解决方案1】:

你在正确的轨道上,只需分配大小为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];
}

【讨论】:

    【解决方案2】:

    将数组的大小设置为 NumberofPlayers。

    PlayerPositions = new int [NumberofPlayers];
    

    【讨论】:

      【解决方案3】:

      为此,您为什么不创建一个 PlayerPositions 列表。

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

      根据用户的输入,将这些对象添加到上述列表中。

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

      【讨论】:

      • 对于最多 4 个玩家,使用静态数组可能是最好的解决方案(取决于对象的复杂性)。至于你的循环,我会使用第二个变量,否则你会失去玩家的数量(除非你使用列表长度)。
      • 这只是一个例子。当然,您希望将用户的输入存储在某处。
      猜你喜欢
      • 2014-06-29
      • 2015-04-27
      • 1970-01-01
      • 2019-10-20
      • 2017-05-14
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多