Search code examples
javaartificial-intelligencegame-theory

How do I print out successors for Tic Tac Toe in java?


I've been working on a Tic-Tac-Toe artificial intelligence lately as a side project. I have thus far succeeded in creating a working prototype of the game that randomly generates the computer moves, making the user win around 90% of time. However, I am trying to make the computer unbeatable through the minimax algorithm. While using the minimax algorithm, I need to get successors for the board, this is what I am having trouble with

This is currently my function:

public static ArrayList<board> successors(board aBoard) {

    board orig = aBoard;
    ArrayList<board> succ = new ArrayList<board>();

    for(int i = 0; i < 9; i++) {
        int row = i / 3;
        int col = i % 3;

        if(!orig.gameBoard[row][col].filled) {
            System.out.println(row);
            System.out.println(col);
            System.out.println("Row: " + row + " Column: " + col);
            board newBoard = orig;
            //newBoard.gameBoard[row][col].filled = true;
            //newBoard.gameBoard[row][col].index = 2;
            succ.add(newBoard);
        }


    }

    System.out.println("Number of successors: " + succ.size());


    int emptyIndex = 0;
    for(int i = 0; i < succ.size(); i++) {
        //find the empty index
    //  System.out.println(emptyIndex / 3);
    //  System.out.println(emptyIndex % 3);
    //  System.out.println(succ.get(i).gameBoard[emptyIndex / 3][emptyIndex % 3].index + "\n");
        while(succ.get(i).gameBoard[emptyIndex / 3][emptyIndex % 3].index != 0) {
            emptyIndex++;
            //System.out.println(emptyIndex + " is a good index");
        }

        System.out.println("Empty Index " + emptyIndex);
        System.out.println("i: " + i);

        succ.get(i).gameBoard[emptyIndex / 3][emptyIndex % 3].index = 2;
        succ.get(i).gameBoard[emptyIndex / 3][emptyIndex % 3].filled = true;




    }

    return succ;
}

It DOES initially get the number of successors correct, it's just that the outputs are off. For example I initially make the first move as follows:

https://i.sstatic.net/Bd47q.jpg

but the results should include all the possible moves the computer can make. Instead it outputs this:

https://i.sstatic.net/gIK2G.jpg

What am I doing wrong? I have been trying to solve this problem for 2 days now.


Solution

  •  board newBoard = orig;
    

    newBoard will point to orig, so all changes made to newBoard will also be made to orig, and vice versa. when the AI makes it's move on newBoard, the move is made to the original board as well, since they both point to the same object.

    you'll want to create a new board object identical to the original board, then make changes to that before adding it to the arraylist. when copying the board state over, take care not to copy references like classes and arrays, and instead use new instances.