MinMax算法无法按预期工作

时间:2015-12-14 15:09:29

标签: javascript algorithm minmax

我正在构建一个tic tac toe游戏(Free Code Camp上的一个项目),并且已经实现了一个minmax算法来决定计算机玩家接下来应该选择哪个方格。

在我测试过的所有情况下,它都按预期工作,但以下情况除外:

var userIs = 'o'
var computerIs = 'x'

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

function nextMove(board, player) {
  var nextPlayer;
  if (computerIs !== player) {
    nextPlayer = userIs; 
  } else {
    nextPlayer = computerIs; 
  }
  if (isGameOver(board)) {
    if (player === userIs) {
      return {
        "willWin": -1,
        "nextMove": -1
      };
    } else {
      return {
        "willWin": 1,
        "nextMove": -1
      };
    }
  }

  var listOfResults = [];

  if (countInArray(board, '-') === 0) {
    return {
        "willWin": 0,
        "nextMove": -1,
      };
  }

  var _list = [];//keeping track of avalible moves
  for (var i=0; i < board.length; i++) {
    if (board[i] === '-') {
      _list.push(i);
    }
  }
  for (var j = 0; j < _list.length; j++) {
    board[_list[j]] = player;
    var nextTry = nextMove(board, nextPlayer);
    listOfResults.push(nextTry.willWin);  
    board[_list[j]] = '-';
  }
  if (player === computerIs) {
     var maxele = Math.max.apply(Math, listOfResults);
     return {
      "willWin": maxele,
      "nextMove": _list[listOfResults.indexOf(maxele)] 
     };
  } else {
    var minele = Math.min.apply(Math, listOfResults);
    return {
      "willWin": minele,
      "nextMove": _list[listOfResults.indexOf(minele)] 
    };
  }
}

function isGameOver(board) {
  //horizontal wins
  var gameOver = false;
  var rowOffset = [0,3,6];
  rowOffset.forEach(function(row){
     if (board[row] === board[row + 1]  && board[row + 1]  === board[row + 2] && board[row] !== "-") {
      gameOver = true;
     }
  });
  //vertical wins
  var colOffset = [0,1,2];
  colOffset.forEach(function(col){
    if (board[col] === board[col + 3] && board[col + 3] === board[col + 6] && board[col] !== "-" ){
      gameOver = true;
    }
  });

  ///diag wins
  if (board[0] === board[4] && board[4] === board[8]  && board[8] !== "-" ) {
    gameOver = true;
  }
  if (board[2] === board[4] && board[4] === board[6] && board[6] !== "-" ) {
    gameOver = true;
  }
 return gameOver;
}

nextMove(["x", "x", "o", "o", "x", "-", "-", "-", "o"], computerIs)

返回的地方:{willWin: 1, nextMove: 5},我希望{willWin: 1, nextMove: 7}

我正在使用Python中的示例实现:https://gist.github.com/SudhagarS/3942029返回预期的结果。

你能看到会导致这种行为的事情吗?

1 个答案:

答案 0 :(得分:0)

我添加了一些日志记录,发现我没有正确地在玩家之间翻转。

切换:

 if (computerIs !== player) {
    nextPlayer = userIs; 
  } else {
    nextPlayer = computerIs; 
  }

为:

if (computerIs === player) {
    nextPlayer = userIs; 
  } else {
    nextPlayer = computerIs; 
  }
当游戏结束时,

并将得分(-1转换为11转换为-1)为胜利者提供了反转似乎已经完成了诀窍。