MiniMax Algorithm for Tic Tac Toe failure

杀马特。学长 韩版系。学妹 提交于 2019-12-25 04:56:21

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/21100216/minimax-algorithm-for-tic-tac-toe-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!