Search code examples
algorithmminimax

Minimax recurse back up the tree


When I recurse back up, my board gets all messed up.

How can I return to the previous board without always copying (my minimax needs to be fast performance wise)

My code:

 for all possible moves:
            board.apply(move);
            int currentScore = minimax(board, depth - 1, false); // recursive call
            int newScore = Math.max(value, currentScore);
            // Undo move on the board or create a temp board for recursive calls, as the recursive calls will mess up the current board
            board.undo(move);

I thought of an undo method in the Board class that takes a move and undo it, but will that get me back to my current board?


Solution

  • Yes as long as you undo all the moves you apply in the opposite order, you'll get back the original board. The move itself object would not normally carry enough information to undo itself, though, so an implementation would look more like:

    for all possible moves:
        // apply the move and remember how to undo it
        undomove = board.apply(move);
    
        // minimax function promises to return the board unmodified
        int currentScore = minimax(board, depth - 1, false); // recursive call
        int newScore = Math.max(value, currentScore);
    
        // Undo move to recover the original board
        board.apply(undomove);