[英]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? 有谁知道如何解决这一问题?
Couple of issues. 几个问题。 First, you have a variable
number
and a parameter number
. 首先,您有一个变量
number
和一个参数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: 其次,您仅与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++;
You would have to add a check to see if any space is still available or not to avoid the loop going to infinity. 您将必须添加检查以查看是否还有可用空间,以避免循环变为无穷大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.