从一个列表中随机移除一个项目 C#

3

这是我在这里的第一个问题。我正在尝试使用按钮和列表制作匹配游戏。我正在使用列表使用字母表示图像,当使用一个字母时,它应该从列表中删除该字母,减少列表中的项数。但是我得到了“索引超出范围”的错误。任何帮助都将不胜感激。 提前致谢, Rhys

 Random random = new Random();

    List<string> icons = new List<string>() 
{ 
    "!", "!", "N", "N", ",", ",", "k", "k",
    "b", "b", "v", "v", "w", "w", "z", "z"
};


    Button[,] btn = new Button[4, 4];
    //Random r = new Random();            // Random variable
    public GameWindow()
    {
        InitializeComponent();

        for (int x = 0; x < 4; x++)
        {

            for (int y = 0; y < 4; y++)
            {

                btn[x, y] = new Button();
                btn[x, y].SetBounds(80 * x, 80 * y, 80, 80);
                btn[x, y].FlatAppearance.BorderSize = 1;
                btn[x, y].Click += new EventHandler(this.btnEvent_Click);
                btn[x, y].BackColor = System.Drawing.ColorTranslator.FromHtml("#35014F");
                Controls.Add(btn[x, y]);
                btn[x, y].Font = new Font("Webdings", 50, FontStyle.Regular);
                AssignIconsToButtons(btn[x, y]);




            }
        }

    }


    void AssignIconsToButtons(Button ButtonToAssign)
    {
        foreach (Button control in this.Controls)
        {

            Button iconButton = control as Button;

            if (iconButton != null)
            {


                int randomNumber = random.Next(icons.Count);
                //MessageBox.Show(Convert.ToString(randomNumber));
                iconButton.Text = icons[randomNumber];
                //iconButton.ForeColor = iconButton.BackColor;
                icons.RemoveAt(randomNumber);

            }

错误发生在哪一行? - DavidG
如果 icons 是空的,icons.Count 将会是 0random.Next(0) 会产生 0 作为随机数。如果你尝试访问一个空数组的第 0 个元素,你将会得到一个越界异常。 - Corak
它不喜欢这个操作:iconButton.Text = icons[randomNumber]; - PremiumAluminium
快速而简单的解决方法是,在尝试删除第(n-1)个位置上的项目之前,仅需检查集合是否不为空并且至少包含n个项目。但更好的解决方法是确保您永远不会生成大于(n-1)的随机数,当然;-)正如上面的评论中所解释的那样,我认为这可能是一个很好的答案。 - Davide Piras
3个回答

3

尝试像这样:(Random.Next(Int32, Int32))

if (iconButton != null && icons.Count > 0)
{
    int randomNumber = random.Next(0, icons.Count);
    //MessageBox.Show(Convert.ToString(randomNumber));
    iconButton.Text = icons[randomNumber];
    //iconButton.ForeColor = iconButton.BackColor;
    icons.RemoveAt(randomNumber)
}

3
代码不正确。请注意在 random.Next(min, max) 中,max 值是被排除在外的,因此调用应该是 Next(0, icons.Count) 或者更好的是 Next(icons.Count) - Frank Sebastià

1
您的随机数生成应该是:

int randomNumber = random.Next(icons.Count-1);

这是因为你的数组从0开始计数,而count告诉你列表中对象的数量。

我已经尝试过了,但是出现了另一个错误,提示最大值必须大于零。 - PremiumAluminium
在尝试移除项目之前,请确保icons.count大于1,因为我认为错误发生在游戏的后期。 - KrisJones

1
感谢NeverHopeless的帮助,现在我的盒子上只显示了四张图片,而不是十六张。编程的乐趣就在于此,感谢你的帮助。
  if (iconButton != null && icons.Count > 0)
     {


int randomNumber = random.Next(0, icons.Count-1);
//MessageBox.Show(Convert.ToString(randomNumber));
iconButton.Text = icons[randomNumber];
//iconButton.ForeColor = iconButton.BackColor;
icons.RemoveAt(randomNumber)
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接