如何检查多个矩形是否重叠?

时间:2017-08-01 15:15:33

标签: java arrays rectangles

Square[] testSquares = new Square[3];

public SquareTester (){
    for(int i = 0; i < testSquares.length; i++){
        testSquares[i] = new Square();
    }
}

public void paint(Graphics g) {
    for (int i = 0; i<testSquares.length; i++){
        testSquares[i].display(g);
    }

    if (testSquares[0].overlaps(testSquares[1])) {
        testSquares[0].changeColor(Color.YELLOW);
        testSquares[1].changeColor(Color.GREEN);
        g.setFont(new Font ("Comic Sans", Font.BOLD,35));
        g.drawString("HOLA, IT OVERLAPPED!", 0, 600);
    }
}

上面是制作正方形数组的代码,当两个正方形重叠时会改变颜色。我想更改此代码,以便在整个数组中的任何方块重叠时更改颜色。 (我的重叠方法已经完成了。无需编写代码。)

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

public void paint(Graphics g) {

    boolean[] overlap = new boolean[testSquares.length];
    for (int i=0; i<testSquares.length; i++)
    {
        if(!overlap[i])
        {
            for (int j=i; j<testSquares.length; j++)
            {
                if(testSquares[i].overlaps(testSquares[j]))
                {
                    overlap[i] = overlap[j] = true;
                    break;
                }
            }
        }
    }

    // now use overlap to display squares as overlapped or not
}