Java Creating a Copy of a class

Viewed 32

I want to copy an object, I tried clonable but failed. To Implement minimax function I need to create a copy of the board class and check the best move

in my AIPlayer class

private int pickBestMove(Piece piece){
        int bestScore = 0;
        int bestCol = r.nextInt(board.NUM_OF_COLS);
        int[] validLocations = getValidLocations();
        for (int c = 0; c < validLocations.length; c++) {
             int row = board.findNextAvailableSpot(c);

             Board tempBoard = new BoardImpl(board.getBoardUI()); //Need to copy the board object here

             tempBoard.updateMove(c, row, piece);
             int score = scorePosition(tempBoard, piece);
             if(score > bestScore){
                 bestScore = score;
                 bestCol = c;
             }
        }
        System.out.println("Best Move is " + bestCol);
        return bestCol;
    }

Board is a interface, and BoardImplement is it's subclass

public interface Board {}

I tried the clonnable

public class BoardImpl implements Board, Cloneable {
//My other stuff
public BoardImpl clone() {
        try {
            BoardImpl clone = (BoardImpl) super.clone();
            // TODO: copy mutable state here, so the clone can't change the internals of the original
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

I tried adding this code to AIPlayer class (Mentioned above)

     Board tempBoard = (Board) board.clone();

but it failed,

'clone()' has protected access in 'java.lang.Object

What are the solution that I can do for this?

Thanks for your time.

0 Answers
Related