Tic tac toe minimax algorithm

245 views Asked by At

I am trying to write a tic tac toe game for free code camp.

I want to implement the minimax algorithm.

I found this: https://jsfiddle.net/9486vod0/1/ which is as bad as my code right now.

I believe the problem lies in the way the recursion works, but I am not sure.

This is the full project so far: 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

There are 0 answers