动态按钮随机分布时如何防止重叠?

时间:2018-08-27 10:56:07

标签: c#

我正在尝试做一个游戏,为此,我需要随机放置按钮,而又不要互相重叠。当我运行代码时,按钮有时彼此重叠。我不知道如何防止这种情况。我该如何预防呢?

这是我的代码:

Random rnd = new Random();
        int x, y,n,c= 0;
        private void beginnerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<Button> buttons = new List<Button>();
            List<int> mynumber = new List<int>() {0,1,2,3,4,5,6,7,8,9};
            List<Color> mycolor = new List<Color>() { Color.AliceBlue, Color.AntiqueWhite, Color.Aqua, Color.Aquamarine, Color.Azure, Color.Beige, Color.Blue, Color.Brown, Color.Chocolate, Color.DarkOrange, Color.Red,Color.Red,Color.Yellow,Color.SpringGreen };
            for (int i = 0; i < 5; i++)
            {   
                Button btn = new Button();
                btn.Size = new Size(50, 50);
                for (int j = 0; j < 5; j++)
                {
                    x = rnd.Next(0, 500);
                    y = rnd.Next(0, 430);
                    n = rnd.Next(0, 10);
                    c = rnd.Next(0, mycolor.Count);
                    btn.Location = new Point(x, y);
                    btn.Text = mynumber[n].ToString();
                    btn.BackColor = Color.Black;
                    btn.Font = new Font("Tahoma", 12,FontStyle.Bold);
                    btn.ForeColor = mycolor[c];
                    buttons.Add(btn);
                    pnlbtn.Controls.Add(btn);
                }




            }

0 个答案:

没有答案