0

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

4
  • You have to vary X and Y independently. Use a nested for loop, varying X in the outer loop and varying Y in the inner loop. Commented Oct 22, 2023 at 18:15
  • There is the Graphics#drawPolygon method. Commented Oct 22, 2023 at 21:45
  • 1
    It’s a weird requirement, as the two loops are comprehensible and easy to read and that’s the most important aspect of program code. However, you can do it in a single loop, e.g. 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); } As said, I’d stick to the two loops. And well, to me, this grid doesn’t look like a backgammon board, not even remotely. Commented Oct 23, 2023 at 10:59
  • 1
    Thanks for the flowers, however, for any practical purpose, a two loops solutions stays preferable, as the single loop solution serves no other purpose than “being awesome” and solving the artificial requirement. Commented Oct 30, 2023 at 16:47

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.