Search code examples
c#arrayspictureboxoverlapoverlapping

Colliding picture boxes, random location not working


I've been trying to make a array of images that are created randomly in a space, the thing is when they overlap, they are not changing they're location.

    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);
    }

Does anyone know how to fix this?


Solution

  • Couple of issues. First, you have a variable number and a parameter number. Not good:

    int number;
    private void addX(int number)
    

    Just change it to:

    private void addX()
    

    Secondly, you are only comparing against PictureBox1, so all of the PictureBoxes you are adding aren't checking the other PictureBoxes, so you can try something like this:

    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++;
    

    You would have to add a check to see if any space is still available or not to avoid the loop going to infinity.