Tic tac toe minimax算法

时间:2016-12-17 07:25:24

标签: javascript algorithm max minimax

我正在尝试为免费代码阵营编写一个tic tac toe游戏。

我想实现minimax算法。

我发现了这个:https://jsfiddle.net/9486vod0/1/这与我现在的代码一样糟糕。

我认为问题在于递归的工作方式,但我不确定。

到目前为止,这是完整的项目:http://codepen.io/periman/pen/rWovrm?editors=0010

function max(gameb) {

  if (checkboard(gameb) !== 'next') {
    return gameb;
  }

  var bestscore = -1000;
  var bestmove = [];
  var newscore;
  var posmoves = possibleMoves(gameb);

  for(var i = 0; i < posmoves.length; i++) {
    var newboard = gameb.slice();
    newboard[posmoves[i]] = true;
    newscore = scoresofar(min(newboard));

    if (newscore > bestscore) {
      bestscore = newscore;
      bestmove = newboard;
    }
  }
  return bestmove;
}

function min(gameb) {

  if (checkboard(gameb) !== 'next') {
    return [gameb, scoresofar(gameb)];
  }
  var badscore = 1000;
  var worstmove = [];
  var newscore;
  var posmoves = possibleMoves(gameb);

  for(var i = 0; i < posmoves.length; i++) {
    var newboard = gameb.slice();
    newboard[posmoves[i]] = false;
    newscore = scoresofar(max(newboard));

    if (newscore < badscore) {
      badscore = newscore;
      worstmove = newboard;
    }
  }
  return worstmove;
}

0 个答案:

没有答案