避免随机重复的颜色

时间:2014-12-26 16:45:13

标签: c#

我一直在尝试制作游戏“Mastermind”,我试着点击“显示”按钮,它会从ROYGBIV生成3种颜色。(已经完成)

但是现在我需要做一个声明,比较生成的随机颜色。 这是代码的一部分

public partial class Form1 : Form
    {
        Color[] RandomColor = new Color[7] { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet };
        Random r = new Random();

        public Form1()
        {
            InitializeComponent();

        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            btnShow.Text = "Hide";

            for (int i = 0; i < RandomColor.Length; i++)
            {
                int RandomColorNum = r.Next(0, RandomColor.Length);

                switch (i)
                {
                    case 1: pnlNPC1.BackColor = RandomColor[RandomColorNum];
                        break;
                    case 2: pnlNPC2.BackColor = RandomColor[RandomColorNum];
                        break;
                    case 3: pnlNPC3.BackColor = RandomColor[RandomColorNum];
                        break;
                }

            } 

            pnlNPC1.Visible = true;
            pnlNPC2.Visible = true;
            pnlNPC3.Visible = true;



         }

谢谢你们,一切顺利!

1 个答案:

答案 0 :(得分:0)

以下是您可以使用的功能:

int[] PickIntegers(int amountToPick, int maxSize)
{
    List<int> numbers = new List<int>(amountToPick);

    for (int x = 0; x < amountToPick; x++)
    {
        int n = 0;
        while (true)
        {
            n = r.Next(0, maxSize);
            if (!numbers.Contains(n))
            {
                numbers.Add(n);
                break;
            }
        }
    }

    return numbers.ToArray();
}

然后你可以这样打电话:

private void btnShow_Click(object sender, EventArgs e)
{
    btnShow.Text = "Hide";

    int[] numbers = PickIntegers(3, RandomColor.Length);

    pnlNPC1.BackColor = RandomColor[numbers[0]];
    pnlNPC2.BackColor = RandomColor[numbers[1]];
    pnlNPC3.BackColor = RandomColor[numbers[2]];


    pnlNPC1.Visible = true;
    pnlNPC2.Visible = true;
    pnlNPC3.Visible = true;
 }

注意:此代码尚未经过测试。它可能包含拼写错误。