试图阻止随机生成的图片框不相交

问题描述

我正在使用Windows窗体上的程序,该程序生成随机坐标点以绘制鱼。我需要鱼之间不再相交,但是我编写的代码无法正常工作。生成的坐标应放入矩形,然后对照所有其他点矩形进行检查。鱼保持相交。知道为什么吗? Code I wrote to stop the intersection.

for (int i = 0; i < fishNumber; i++)
{
    // Checks for overlapping
    fishX = x.Next(200,3100);
    fishY = y.Next(100,1620);

    fishPoints.Add(new Point(fishX,fishY));
    for (int j = 0; j < i; j++)
    {
        while (i != 0 && new Rectangle(fishPoints[i],new Size(200,134)).IntersectsWith(new Rectangle(fishPoints[j],134))))
        {
            fishPoints.RemoveAt(i);
            fishX = x.Next(200,3100);
            fishY = y.Next(100,1620);
            fishPoints.Add(new Point(fishX,fishY));
        }
    }
}

解决方法

尝试以下类似的方法。在确定它不与任何其他鱼相交之后,才添加点:

Size fishSize = new Size(200,134);
for (int i = 0; i < fishNumber;i++)
{
    Point pt;
    bool collided;
    do
    {
        collided = false;
        pt = new Point(x.Next(200,3100),y.Next(100,1620));
        Rectangle rcNewFish = new Rectangle(pt,fishSize);
        foreach(Point otherPt in fishPoints)
        {
            if (rcNewFish.IntersectsWith(new Rectangle(otherPt,fishSize)))
            {
                collided = true;
                break;
            }
        }
    } while (collided);
    fishPoints.Add(pt);
}