javajava-2d

Java 2D graphics backgammon table (algorithm question)


My problem is I need to use only one drawLine. I couldn't figure out how am I supposed to make changes at the same time in x and y while not messing with one and another. I can't use a rectangle.

int x = 25;
int y = 25;

for (int i = 0; i <=8; i++) {
    g2d.drawLine(x, y, x+160, y);
    y+=20;
}

x = 25;
y = 25;

for (int i = 0; i <=8; i++) {
    g2d.drawLine(x, y, x, y+160);
    x+=20;
}

This is what I expected


Solution

  • Holger Sama's Answer (one for):

        int startX = 25,
        startY = 25,
        endX = startX + 160,
        endY = startY + 160;
    for (int i = 0; i <= 17; i++) {
        int h = i & 1,
            v = h ^ 1,
            x = startX + v * (i >> 1) * 20,
            y = startY + h * (i >> 1) * 20;
        g2d.drawLine(x, y, x * v + endX * h, y * h + endY * v);
    }
    

    My Answer (nested for):

        int endy = 0, endx = 160, xIncreaser  = 0, x = 25;
    for (int i = 0; i <= 9; i++){
        int y = 25;
        x+=xIncreaser;
        if (i == 1)
            x-=20;
        for (int j = 0; j <= 8; j++){
            if (y+endy>185)
                break;
            g2d.drawLine(x,y, x+endx, y+endy);
            y+=20;
        }
        xIncreaser  = 20;
        endy = 160;
        endx = 0;