javaChipFrapp
javaChipFrapp

Reputation: 103

Making a chessboard with graphics

I'm trying to make a chessboard with graphics in Java (with the pixels themselves - not just pasting squares), and it doesn't work quite the way I want it to. Here's my code:

int a = 0, b = 0;
for(int y = 30; y < getHeight() - 318; y++){
   for(int x = 30; x < getWidth() - 70; x++){
      if((b % 2 != 0)){
        x+=80;
        b++;     //if odd row, skip to next horizontal square to color black
      }
      if((x % 80 == 30) && (a % 2 == 0)){
        g.setColor(Color.BLACK);
        g.fillRect(x, y, 80, 80); //make squares of 80 x 80 pixels
      }     
      x+=79;
      a++;
  }
y+=79;
b++;
}

(Don't worry about the - 318 and - 70 and such - I'll fix them later, they're not of much consequence right now.) The first row of the chessboard is normal - but the rest of the rows are offset because the rest of the first column is white, and not alternating with black. There's something wrong with b, but I'm not sure how to fix it. Any help is greatly appreciated!

Upvotes: 0

Views: 1001

Answers (1)

user3125280
user3125280

Reputation: 2829

You seem to be a little confused about which variables to use when you loop through the board. In some places you use a and b, which go up by 1 (it a = 1 and b = 2, they would seem to be referring to the square 1 step right from the top and two steps down), in other places you loop with x and y which are referring to screen pixels

I changed it a little to only use a and b, and we determine x and y only when we draw the squares. I also changed the logic to determine when a square is black or white - this might be wrong but there are only two ways to draw the chess board as either beginning black or beginning white.

//int a = 0, b = 0; // we will loop thorugh a,b instead
for(int a = 0; a < 8; a++){
   for(int b = 0; x < 8; x++){
      //b is for the horizontal axis and a for vertical
      if((a + b) % 2 == 0){
        g.setColor(Color.BLACK);
        g.fillRect(30 + b * 80, 30 + a * 80, 80, 80); //make squares of 80 x 80 pixels
      }     
   }
}

Upvotes: 2

Related Questions