Rubee
Rubee

Reputation: 129

Loop to draw a piece on a grid

I have a 640x640 grid that maps to an 8x8 2D array. I need to be able to draw an oval in the place that the user clicks and I'm trying to figure out a loop to do it instead of typing multiple if statements.

For example I can write this for each square on the board and it will draw the desired shape with no issue.

oldx = event.getX(); 
oldy = event.getY(); 
if(oldx<=80&&oldy<=80){
board[0][0]=1; 
    repaint(); 

}

I'm trying to make a loop and this is what I have so far, it is not working out well though. It prints in undesired locations. I think the way I have it here is that it only prints in locations that are divisible by 80. I need to take in the x and y coordinates to the 2D array.

    int x1 = oldx/80;
    int y1 = oldy/80;
    for(int r=0; r<8; r++){
      for(int c=0; c<8; c++){
          board[x1][y1] = 1;
           repaint();
         }  
       }
    }

Any help is appreciated.

Upvotes: 0

Views: 85

Answers (2)

Conor McKernan
Conor McKernan

Reputation: 41

This will get it working for you.

    boolean found = false;
    while(found!=true){
    for(int r=0; r<8; r++){
        for(int c=0; c<8; c++){
        if(y1==c&&x1==r){
            board[r][c] = 1;
            found = true;
            repaint();
                }
            }
        }
    }
}

Upvotes: 2

jzd
jzd

Reputation: 23639

You seem like you are on the right path. However, you don't have your condition in the loop example. You need to add an if() statement inside your double for loop to check to see if the selected X and Y match the current square you are looping through.

Upvotes: 2

Related Questions