Question

I'm trying to implement a minimax algorithm for tic tac toe with alpha-beta pruning. Right now I have the program running, but it does not seem to be working. Whenever I run it it seems to input garbage in all the squares. I've implemented it so that my minimax function takes in a board state and modifies that state so that when it is finished, the board state contains the next best move. Then, I set 'this' to equal the modified board. Here are my functions for the minimax algorithm:

void board::getBestMove() {
  board returnBoard;
  miniMax(INT_MIN + 1, INT_MAX -1, returnBoard);

  *this = returnBoard;
}

int board::miniMax(int alpha, int beta, board childWithMaximum) {
  if (checkDone())
    return boardScore();

  vector<board> children = getChildren();
  for (int i = 0; i < 9; ++i) {
    if(children.empty()) break;

    board curr = children.back();
    if (curr.firstMoveMade) { // not an empty board
      board dummyBoard;
      int score = curr.miniMax(alpha, beta, dummyBoard);

      if (computerTurn && (beta > score)) {
        beta = score;
        childWithMaximum = *this;
        if (alpha >= beta) break;
      } else if (alpha < score) {
        alpha = score;
        childWithMaximum = *this;
        if (alpha >= beta) break;
      }
    }
  }
  return computerTurn? alpha : beta;
}

vector<board> board::getChildren() {
  vector<board> children;

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      if (getPosition(i, j) == '*') { //move not made here
        board moveMade(*this);
        moveMade.setPosition(i, j);
        children.push_back(moveMade);
      }
    }
  }

  return children;
}

And here are my full files if someone wants to try running it:

.cpp : http://pastebin.com/ydG7RFRX .h : http://pastebin.com/94mDdy7x

No correct solution

OTHER TIPS

There may be many issues with your code... you sure posted a lot of it. Because you are asking your question it is incumbent on you to try everything you can on your own first and then reduce your question to the smallest amount of code necessary to clarify what is going on. As it is, I don't feel that you've put much effort into asking this question.

But maybe I can still provide some help:

void board::getBestMove() {
  board returnBoard;
  miniMax(INT_MIN + 1, INT_MAX -1, returnBoard);

  *this = returnBoard;
}

See how you are saying *this = returnBoard.

That must mean that you want to get a board back from miniMax.

But look at how miniMax is defined!

int board::miniMax(int alpha, int beta, board childWithMaximum)

It accepts childWithMaximum via pass by value so it cannot return a board in this way.

what you wanted to say was probably:

int board::miniMax(int alpha, int beta, board & childWithMaximum)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top