Search code examples
javaalgorithmn-queens

Eight Queens - Diagonal Movement


I have an 8 by 8 chess board that I am trying to implement the eight queen puzzle. In my game I have made a function that checks for the movement of queens and once a button gets pressed in my board, all rows and columns that a specific queen could move to get turned off so that no two queens are attacking each other. I am stuck however trying to figure out how I could get all diagonal buttons to get turned off as well in my code.

private JButton[][] Squares = new JButton[8][8];
for (int i = 0; i < Squares.length; i++) {
                for (int j = 0; j < Squares[i].length; j++) {
                    if(Squares[i][j].getModel().isPressed()){
                    for (int x=0; x<8; x++){
                        Squares[i][x].setEnabled(false); //turns off column buttons
                        Squares[x][j].setEnabled(false); //turns off row buttons
                        //Squares[i][j+1].setEnabled(false);
                        //Squares[i+1][j-1].setEnabled(false);


        }

What do I need to do in order to disable all diagonal buttons once a queen gets placed on the chessboard?

EDIT: I noticed that if I do Squares[x][x].setEnabled(false); then it will give me one of the two diagonals, however this only gives the diagonal one time and after clicking on a second button everything breaks.


Solution

  • You start out from [i][j], and keep advancing (using your loop var x) on both rows an columns in parallel. The only tricky part is how to avoid falling off the edge of the board. Note that unlike the rows/columns, your diagonal won't necessarily have 8 squares

    one way to do this, using the same basic loop over x, is -

    if (i+x < Squares.length && j+x < Squares[i].length)
        Squares[i+x][j+x].setEnabled(false);             
    if (i-x >= 0 && j-x >= 0)
        Squares[i-x][j-x].setEnabled(false);             
    if (i-x >= 0 && j+x < Squares[i].length)
        Squares[i-x][j+x].setEnabled(false);             
    if (i+x < Squares.length && j-x >=0)
        Squares[i+x][j-x].setEnabled(false);