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,它返回预期的结果。

你能看到会导致这种行为的东西吗?


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

交换:

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

至:

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

并且在比赛结束时为胜利者返回的得分( -111-1 )似乎已经完成了这个技巧。

链接地址: http://www.djcxy.com/p/56383.html

上一篇: MinMax algorithm not working as expected

下一篇: MinMax Algorithm for Tic Tac Toe