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

Above is the code that makes the array of squares, and changes color when two of them overlap. I want to change this code so that it changes color if any of the squares in the whole array are overlapping. (My overlaps method is done already. No need to code that.)

tima
  • 1,498
  • 4
  • 20
  • 28
  • So, you need us to code up the `.overlaps()` method for you, eh? – Rabbit Guy Aug 01 '17 at 15:16
  • 2 for loops checking testSquare[i] vs testSquare[j] wouldn't do it ? I don't see how you would need help for that... – Carele Aug 01 '17 at 15:20
  • not sure what the question is tbh – nafas Aug 01 '17 at 15:21
  • Test for overlapping inside the for loop before you render? And test for all other squares and not just [0] and [1] – RobCo Aug 01 '17 at 15:23
  • You need to create a rectangle which occupies the overlapping space and render it on the `Graphics` pane. If you change `overlaps` to return the top left and bottom right coordinates of the intersecting rectangle (and null if there is no overlap), you already have the dimensions of the intersect. Just create a `Rectangle` object to those dimensions, and render it. – Alex Aug 01 '17 at 15:24
  • As an aside, why comic sans? Bold comic sans noless. Surely there is a better way...... – Alex Aug 01 '17 at 15:25

1 Answers1

0

How about something like this:

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
}
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
  • This wouldn't provide the dimensions of the intersecting rectangles, just a list of bools denoting which overlap. The overlapping areas would therefore need to be calculated in another loop iterating over the `overlap` array. If instead an array of `Rectangle` was created, the overlapping area could be calculated in the main loop, and rendering is just a case of iterating the rectangles and drawing them – Alex Aug 01 '17 at 15:26