javascript - 在 Javascript 中实现 minimax 算法

标签 javascript algorithm minimax

作为个人练习,我正在尝试实现一个基于 minimax 的井字游戏。我一直在研究我在网上找到的各种语言的例子。我的实现似乎可以正常工作,但在某些边缘情况下 AI 会失败。你可以玩我的版本here

如果您选择 3 个 Angular ,然后选择中心,您将获胜。否则它似乎可以正确执行。我可以在不同的游戏状态下手动运行我的 minmax() 函数,它似乎对 AI 的第一步得分不正确。我担心我实现算法的方式存在根本性的错误。

这是我的代码:

// Board state 'object'
function State(old) {
  // Prior board states can be loaded in during minmax recursion
  if (typeof old !== 'undefined') {
    this.board = old.board.slice(0);
  } else {
  // Otherwise start with empty board
    this.board = ['E','E','E','E','E','E','E','E','E'];  
  }
  // Terminal game flag
  this.result = 'active';
  // Current player flag
  this.turn = "X";
  // Label to identify move that results in this state during recursion
  this.element = "";
  // Function to switch active player for minmax scoring
  this.advanceTurn = function() {
    this.turn = this.turn === "X" ? "O" : "X";
  }
  // Function to determine if game is complete
  this.isTerminal = function() {
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i++) {
      const [a, b, c] = lines[i];
      if (this.board[a] !== 'E' && this.board[a] === this.board[b] && this.board[a] === this.board[c]) {
        this.result = this.board[a];
        return true;
      } 
    } 
    if (this.moves().length < 1) {
        this.result = 'DRAW';
        return true;
    }
    return false;
  }
  // Function to find all possible moves
  this.moves = function() {
    arr = this.board.reduce(function(array,el,index){
      if (el === 'E') {
        array.push(index);
      }
      return array;
    },[]);
    return arr;
  }
}

// Recursive minmax function
function minmax(state) {
  // 1) If the state is terminal, return the score from O's perspective
  if (state.isTerminal() === true) {
    if (state.result === 'X') {
      return  -10; 
    } else if (state.result === 'O') {  
      return 10;
    } else {
      return 0;
    }
  } 

  // Generate list of possible new game states (moves) 
  newStatesSet = state.moves().map(function (el) {
    var newState = new State(state);
    newState.board[el] = state.turn.slice(0);
    newState.advanceTurn();
    newState.element = el;
    return newState;
  });  

  // Array to hold all child scores
  var newStateScores = [];

  // For each of these states, add the minmax score of 
  // that state to the scoreList
  newStatesSet.forEach(function(newState) {
    var newStateScore = minmax(newState);
    newStateScores.push(newStateScore);
  });
  stateScore = Math.min(...newStateScores);
  return stateScore;
}

function aiMove(state) {
  var possibleScores = [];
  var possibleMoves = [];
  var possibleStates = state.moves().map(function(el) {
    var newState = new State(state);
    possibleMoves.push(el);
    newState.board[el] = 'O';
    possibleScores.push(minmax(newState));
    return newState;
  });
  if (possibleMoves.length < 1) {
    return -1;
  }
  console.log(possibleStates);
  console.log(possibleScores);
  function indexOfMax(arr) {
    var max = arr.reduce(function(a,b) {
      return b > a ? b : a;   
    });
    return arr.indexOf(max);
  }
  return possibleMoves[indexOfMax(possibleScores)];
}  

var game = new State();
game.board = ['E','E','E',
              'O','E','E',
              'X','E','X']
game.turn = 'O';
//console.log(minmax(game));
console.log(aiMove(game));

最佳答案

MiniMini算法

我认为这里的递归 minmax 函数有问题:

stateScore = Math.min(...newStateScores);

这总是计算最小值,所以您实际上是在运行一个算法,其中在递归中 X 和 O 合作使 X 获胜!

(在您的顶层确实使用了 max,但不在递归中。)

您可以根据 state.turn 选择最大值或最小值来解决此问题。

关于javascript - 在 Javascript 中实现 minimax 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062178/

相关文章:

Java Minimax Alpha-Beta 修剪递归返回

javascript - 在 V8 中异步运行 C++ 和 JS 代码

javascript - 绑定(bind)完成后 KnockoutJS 触发回调

JavaScript 方程求解器库

algorithm - 确定输入是否为完美正方形的好算法是什么?

algorithm - 如何从最小最大算法中获得实际移动而不是移动值

javascript - 返回上一页的元标记

python - 使用模平方的 Rabin-Miller 素数测试算法是否正确?

.net - 获取数组中字符串序列在另一个数组上的重叠的算法

python - Minimax:如何用 Python 实现它?