how to fill every second rectangle / Java / acm / chessboard

147 Views Asked by At

I'm currently developing a simple chessboard with Java ACM and I want to fill every second rectangle with a color but I don't know how to.

        for (i = 0; i < 400; i += 50) {
        for (j = 0; j < 400; j += 50) {

            GRect rect = new GRect(100, 100, i, j);
            add(rect);


            }
        }

I tried it with a if statment, but i doesn't worked for me.

2

There are 2 best solutions below

0
On

With your pretty minimal description, here is my solution.

Here is a tile-able representation. 1/2/3/4 represent "cases" keep in mind that this is tile-able

Assuming: i and j are dimensions of the chessboard, 50x50 is the size of a square.

Assuming: Constructor for GRect is (width, height, ipos, jpos), with top left rectangle coordinate system.

Assuming: Only making rectangles for black squares (cases 2 and 3)

Notice: cases 2 is when (i % 100 == 50) AND (

However, what you probably want is a checker board patter:

for (int i = 0; i < 400; i += 50) {
    for (int j = 0; j < 400; j += 50) {
        if (i % 100 == 0) {
            if (j % 100 == 50) {//case 3
                add(new GRect(50,50, i, j));
            }
        } else if (i % 100 == 50) {
            if (j % 100 == 0) { //case 2
                add (new GRect(50,50, i, j));
            }
        }
    }
}

Note: no one has any idea what the constructor of GRect is, so i've made my best guess as to what to do.

0
On

You could hold an ever switching running condition:

boolean white = true;
for (int i = 0; i < 400; i += 50) {
    for (int j = 0; j < 400; j += 50) {
        ...
        white = !white;

Or derive the color from i and j, which then better be [0, 8) indices:

for (i = 0; i < 8; ++i) {
    for (j = 0; j < 8; ++j) {
        boolean white = (i + j) % 2 == 0;
        GRect rect = new GRect(100, 100, i*50, j*50);
        rect.setFillColor(white ? Color.WHITE : Color.BLACK);
        add(rect);
    }
}