碰撞图片框,随机位置不起作用

Colliding picture boxes, random location not working

我一直在尝试制作一组​​在 space 中随机创建的图像,问题是当它们重叠时,它们并没有改变它们的位置。

    int number;

    PictureBox[] X = new PictureBox[100]; 

    public Form1()
    {
        InitializeComponent();
    }

    private void addX(int number)
    {
        Random randomNumber = new Random(DateTime.Now.Millisecond);
        int x = randomNumber.Next(0, reprezentare.Height - 40);
        int y = randomNumber.Next(0, reprezentare.Width - 40);
        X[number] = new PictureBox();
        X[number].Height = 41;
        X[number].Width = 41;
        X[number].SizeMode = PictureBoxSizeMode.Zoom;
        X[number].Image = Properties.Resources.X;

        if(number >= 1)
        {
            while (pictureBox1.Bounds.IntersectsWith(X[number - 1].Bounds)) x = randomNumber.Next(0, reprezentare.Height - 40);
            while (pictureBox1.Bounds.IntersectsWith(X[number - 1].Bounds)) y = randomNumber.Next(0, reprezentare.Width - 40);
        }

        X[number].Location = new Point(x, y);
        reprezentare.Controls.Add(X[number]);
        number++;

        richTextBox1.Text += x + " : " + y;
        richTextBox1.Text += Environment.NewLine;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        addX(number);
    }

有人知道如何解决这个问题吗?

几个问题。首先,您有一个变量 number 和一个参数 number。不好:

int number;
private void addX(int number)

只需将其更改为:

private void addX()

其次,您只是与 PictureBox1 进行比较,因此您添加的所有 PictureBox 都不会检查其他 PictureBox,因此您可以尝试这样的操作:

bool ok = false;
while (!ok) {
  ok = true;
  int x = randomNumber.Next(0, reprezentare.Width - 40);
  int y = randomNumber.Next(0, reprezentare.Height - 40);
  for (int i = 0; i < number; ++i) {
    if (X[i].Bounds.IntersectsWith(new Rectangle(x, y, 41, 41))) {
      ok = false;
      break;
    }
  }
  if (ok) {
    X[number].Location = new Point(x, y);
  }
}
reprezentare.Controls.Add(X[number]);
number++;

您必须添加检查以查看是否有任何 space 仍然可用,以避免循环进入无穷大。