Othello MVC programming is legal move method

104 Views Asked by At

I have a project in a CS class where we make Othello in an MVC format, I've tried making an is legal move in it, but from what I've seen it only looks upward on the board.

I've tried putting it into an array with all the possible moves you can make in it, but that either ended up with an error, or with it saying that every space was a possible move.

This is the code, board is a 2d string array that represents the board of othello, isOffBoard checks if the position is off the board. getSquare checks if the position inputted is a piece of the person playing or not. The direction class is mainly just a 2d array with coordinates to add to make the position go in a specific direction.

public boolean isLegalMove(int[] pos) {
    if (this.board[pos[0]][pos[1]].equals("")) {
        for(int[] direction : Directions.points) {
            int[] newPos = pos;
            vector(direction, newPos);

            if (isOffBoard(newPos) == true || getSquare(newPos) == 1 || getSquare(newPos) == 0) {
                continue;
            }

            while (isOffBoard(newPos) == false && getSquare(newPos) == -1 && getSquare(newPos) != 0) {
                vector(direction, newPos);
                if (getSquare(pos) == getSquare(newPos)) {
                    System.out.println("Legal Move: " + pos[0] + " " + pos[1]);
                    return true;
                }
            }
        }
    }
    return false;
}
1

There are 1 best solutions below

5
On

You have written: int[] newPos = pos; then both variables point to the same array. You should write newPos = pos.clone().

vector(direction, newPos); here will change the common array (pos and newPos).

An if (getSquare(pos) == getSquare(newPos)) { will likely to be always true.

You should tell us what is the error. And which cases are involved.

You also wrote: getSquare(newPos) == -1 && getSquare(newPos) != 0which is redondant.

If you make the table pos constant, it should point to an empty cell. Then

if (getSquare(pos) == getSquare(newPos)) Is wrong. The condition should be if(isOffBoard(newPos) == false && getSquare(newPos) == 1) not something which could be synonymous of if(getSquare(newPos) == 0). In an other word, the condition for a legal move is 0, -1, -1, -1... 1. And here we are testing the 1 cell.